這是我的代碼。我想知道如何組合來自 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]
但取而代之的是:
[]
uj5u.com熱心網友回復:
您應該修改__add__函式以便對交易求和;事實上,當您創建一個新類時,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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/443108.html
