我試圖找到一種方法,讓所有屬性在類內的一個屬性更改后進行評估,而無需在類外呼叫函式。
class Students:
def __init__(self, name, mylist):
self.name = name
self.subjects = mylist
self.credits = len(self.subjects) * 2
def credits_calc(self):
self.credits = len(self.subjects) * 2
return self.credits
john = Students("John", ["Maths", "English"])
print(john.subjects)
print(john.credits)
john.subjects.append("History")
print(john.subjects) # --> subjects attribute updated.
print(john.credits) # --> obviously not updated. Still returns initial value.
我必須在類外呼叫該函式才能更新其他屬性
john.credits_calc() # I know I can take the returned value.
print(john.credits) # --> updated after calling the function.
所以我的問題是如何獲取其他屬性來評估一個屬性是否發生更改,而無需稍后手動呼叫該函式。
uj5u.com熱心網友回復:
您正在尋找的是property裝飾器。您可以添加其他方法,尤其是該屬性的fset和fdel邏輯,下面的代碼僅定義了fget行為。
class Students:
def __init__(self, name, mylist):
self.name = name
self.subjects = mylist
@property
def credits(self):
return len(self.subjects) * 2
john = Students("John", ["Maths", "English"])
print(john.credits) # 4
john.subjects.append("History")
print(john.credits) # 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395738.html
上一篇:從同一個父類的另一個類訪問物件
