【发布时间】:2021-12-26 13:04:49
【问题描述】:
我正在尝试找到一种方法,让所有属性在类内的一个属性更改后进行评估,而无需调用类外的函数。
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.
所以我的问题是如何让其他属性来评估是否更改了一个属性,而无需稍后手动调用该函数。
【问题讨论】:
标签: python class attributes