Home > Blockchain >  How does inheritance of class variables work in Python?
How does inheritance of class variables work in Python?

Time:11-05

I'm trying to get back to Python but I don't get why the following code doesn't work as intended.

class Cat:
    age = 0


class Dog(Cat):
    pass


Dog.age = 1
Cat.age = 2

print(Dog.age, Cat.age)

My output is:

1 2

But why doesn't Dog.age equals 2?

Dog is a subclass of Cat and modifying the class variable of the superclass Cat would normally affect every subclass that inherits the variable as well.

CodePudding user response:

Any property of Dog will override a property inherited from Cat. You can re-define a value in Cat, but it won't matter because it has already been overridden by the child. For example:

class Cat:
    age = 0  # Cat.age = 0


class Dog(Cat):
    pass  # Dog.age = Cat.age = 0


Dog.age=1  # Dog.age = 1, and Dog.age no longer points to Cat.age
Cat.age=2  # Cat.age = 2

print(Dog.age, Cat.age)  # Dog.age is no longer Cat.age. They are completely different

Contrast that with this:

class Cat:
    age = 0  # Cat.age = 0


class Dog(Cat):
    pass  # Dog.age = Cat.age = 0

Cat.age = 10  # Cat.age = 10

print(Dog.age, Cat.age)  # Dog.age points to Cat.age, so Dog.age resolves to 10

CodePudding user response:

Inheritance refers to defining a new class with little or no modification to an existing class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class. The class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class(es), and a method can call the method of a base class with the same name.

class Cat:
    def __init__(self):
        self.age = 2
        self.sound = "meow"


class Dog(Cat):
    def __init__(self):
        super().__init__()
        self.sound = "bark"


cat = Cat()
dog = Dog()

print(f"The cat's age is {cat.age}, and the dog's age is {dog.age}.")
print(f"Cats {cat.sound}, and dogs {dog.sound}.")

The cat's age is 2, and the dog's age is 2.

Cats meow, and dogs bark.


So, you can see the dog.age can inherit from class Cat. Notice the sound part, the method in the derived class overrides that in the base class. This is to say, we wrote the dog sound, it gets preference over the class Cat sound.

  • Related