Search code examples
pythonclass-variables

Update child class variables from base class


I would like to know if there exists a way to update class variables in children from the base/parent. Is there a way for the birthday function to update the appropriate class variable?

I know that perhaps the proper way to do it in this example is to make age an instance variable. But I have a case where I would like to insist on making age a class variable.

class Animal():
    def __init__(self):
        pass

    def birthday(self):
        self.age = self.age + 1


class Cat(Animal):
    age = 4


class Dog(Animal):
    age = 2


d = Dog()
print(Dog.age)
d.birthday()
print(Dog.age)

Solution

  • Set the value on the class.

    class Animal():
        def __init__(self):
            pass
    
        def birthday(self):
            self.__class__.age = self.__class__.age + 1
            # shorter version:
            # self.__class__.age += 1