我對我的這個帶有繼承的程式有疑問,我不知道我是理解錯誤還是代碼錯誤(也許兩者都有),但我真的需要一些幫助。
其他功能正在運行,唯一的問題是當我嘗試通過帳戶(子類)訪問 Saving 類功能時。
class Savings:
def __init__(self):
self.money = 0
self.statement = []
def apply(self, value):
self.money = value
self.statement.append(("Apply", f"${value}"))
class Accounts(Savings):
def __init__(self, client: Client, bank: Bank):
super().__init__()
#other variables
def change_money(self):
print("3 - Apply in Savings")
choose = int(input("Choose: "))
elif choose == 3:
value = float(input("Value to apply: $").replace(",", "."))
super().apply(value)
print(super().money)
else:
pass
當我嘗試訪問貨幣變數時,它說
super().money
AttributeError: 'super' object has no attribute 'money'
我僅使用 Accounts 作為物件進行了測驗,并且貨幣變數發生了變化,
輸入:
a = Accounts()
a.change_money()
a.money
輸出
3 - Apply in Savings
Choose: 3
Value to apply: $100
100.0
但是 Accounts 和 Savings 是不同的類,我需要訪問它并從子類進行更改
拜托,有人可以幫我嗎?
uj5u.com熱心網友回復:
您可以self.apply(value)改用:
class Savings:
def __init__(self):
self.money = 0
self.statement = []
def apply(self, value):
self.money = value
self.statement.append(("Apply", f"${value}"))
class Accounts(Savings):
def change_money(self):
value = float(input("Value to apply: $"))
self.apply(value)
print(self.money)
a = Accounts()
a.change_money() # input, say, 10
print(a.statement) # [('Apply', '$10.0')]
您的物件a繼承了apply附加到自身的方法,因此a可以通過 呼叫自己的方法self.apply。
uj5u.com熱心網友回復:
您不需要呼叫 super,因為它是一個預定義的函式并且是儲蓄賬戶類的一部分。只需呼叫 self.apply(value)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/396528.html
上一篇:Python檔案轉換需要2天多
