Home > front end >  Change variable attribute, evaluate other attributes accordingly
Change variable attribute, evaluate other attributes accordingly

Time:12-27

I am trying to find a way for getting all attributes to evaluate after one attribute change within the class, without calling a function outside the class.

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.

I have to call the function outside the class to to have the other attributes updated

john.credits_calc() # I know I can take the returned value.
print(john.credits) # --> updated after calling the function.

So my question is how to get the other attributes to evaluate if one attribute is changed without the need to manually call the function later.

CodePudding user response:

What you are looking for is the property decorator. There are additional methods you can add on to this, particularly the fset and fdel logic of this attribute, the code below simply defines the fget behavior.

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
  • Related