我試圖找到一種方法,在類內的一個屬性更改后,不調用類外的函數,就可以讓所有屬性都進行求值。
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.
因此,我的問題是,如果一個屬性發生了更改,那么如何讓其他屬性進行計算,而無需稍后手動調用該函數。
你要找的是
property
裝飾師。您可以在此基礎上添加其他方法,特別是此屬性的fset和fdel邏輯,下面的代碼僅定義fget行為。