【问题标题】:Change variable attribute, evaluate other attributes accordingly更改变量属性,相应地评估其他属性
【发布时间】: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


    【解决方案1】:

    您正在寻找的是 property 装饰器。您可以添加其他方法,特别是该属性的 fsetfdel 逻辑,下面的代码简单地定义了 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-13
      • 2018-07-03
      • 1970-01-01
      • 2021-11-25
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多