Home > Software design >  How to combine attributes from 2 objects that are not received upon initialization
How to combine attributes from 2 objects that are not received upon initialization

Time:03-14

This is my code. I would like to know how to combine the "_transactions" attributes from 2 objects.

Could you please help me out?

class Account:

def __init__(self, owner, amount=0):
    self.owner = owner
    self.amount = amount
    self._transactions = []

def add_transaction(self, amount):
    if type(amount) != int:
        raise ValueError("please use int for amount")
    self._transactions.append(amount)

def __add__(self, other):
    name = f"{self.owner}&{other.owner}"
    starting_amount = self.amount   other.amount
    self._transactions  = other._transactions
    return Account(name, starting_amount)

acc = Account('bob', 10)
acc2 = Account('john')
acc.add_transaction(20)
acc.add_transaction(-20)
acc.add_transaction(30)
acc2.add_transaction(10)
acc2.add_transaction(60)
acc3 = acc   acc2
print(acc3._transactions)

The output should be:

[20, -20, 30, 10, 60]

But instead is:

[]

CodePudding user response:

You should modify the __add__ function in order to sum the transactions; infact when you instatiate a new class, the self._transactions attribute is an empty list by default.

class Account:

  def __init__(self, owner: str, amount: int = 0, transactions: list = None):
      self.owner = owner
      self.amount = amount  
      self._transactions = [] if transactions is None else transactions
    
  def __add__(self, other):
      name = f"{self.owner}&{other.owner}"
      starting_amount = self.amount   other.amount
      transactions = self._transactions   other._transactions
      return Account(name, starting_amount, transactions)
    
  def add_transaction(self, amount):
      if type(amount) != int:
          raise ValueError("please use int for amount")
      self._transactions.append(amount)

acc = Account('bob', 10)
acc2 = Account('john')
acc.add_transaction(20)
acc.add_transaction(-20)
acc.add_transaction(30)
acc2.add_transaction(10)
acc2.add_transaction(60)
acc3 = acc   acc2
print(acc3._transactions)

>>> [20, -20, 30, 10, 60]
  • Related