如何组合初始化时未收到的 2 个对象的属性

How to combine attributes from 2 objects that are not received upon initialization

这是我的代码。我想知道如何组合来自 2 个以上对象的“_transactions”属性。

你能帮帮我吗?

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)

输出应该是:

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

而是:

[]

您应该修改 __add__ 函数以便对交易求和;事实上,当你实例化一个新的 class 时,self._transactions 属性默认是一个空列表。

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]