David
David

Reputation: 3026

Changing a static variable of inherited classes

Consider the following code:

class Car():
    velocity = 1

class Chrysler(Car):
    pass

class Ford(Car):
    pass


print(f"Car:\t\t {Car.velocity}")
print(f"Chryler:\t {Chrysler.velocity}")
print(f"Ford:\t\t {Ford.velocity}")
print()
Car.velocity = 3
print(f"Car:\t\t {Car.velocity}")
print(f"Chryler:\t {Chrysler.velocity}")
print(f"Ford:\t\t {Ford.velocity}")
print()
Ford.velocity = 2
Car.velocity = 3
print(f"Car:\t\t {Car.velocity}")
print(f"Chryler:\t {Chrysler.velocity}")
print(f"Ford:\t\t {Ford.velocity}")
print()
Car.velocity = 4
print(f"Car:\t\t {Car.velocity}")
print(f"Chryler:\t {Chrysler.velocity}")
print(f"Ford:\t\t {Ford.velocity}")

The output yields:

Car:         1
Chryler:     1
Ford:        1

Car:         3
Chryler:     3
Ford:        3

Car:         3
Chryler:     3
Ford:        2

Car:         4
Chryler:     4
Ford:        2

First time I changed velocity to three, all inherited classes changed their static variable to three. However, if I change the velocity variable of Ford, I cannot change the velocity variable of Ford anymore just by changing the Car attribute.

Why is that the case? I would have expected Ford to be four as well in the end.

Upvotes: 0

Views: 41

Answers (3)

Ulysses
Ulysses

Reputation: 6015

The code never alters base class static from child class. It creates a new variable for child class. Replace the velocity with velocityX and it will be clarified.

class Car():
    velocity = 1

class Chrysler(Car):
    pass

class Ford(Car):
    pass


Ford.velocityX = 2
Car.velocity = 3
print(f"Car:\t\t {Car.velocity}")
print(f"Chryler:\t {Chrysler.velocity}")
print(f"Ford:\t\t {Ford.velocity}")
print(f"Ford velocityX:\t\t {Ford.velocityX}")
print()
Car.velocity = 4
print(f"Car:\t\t {Car.velocity}")
print(f"Chryler:\t {Chrysler.velocity}")
print(f"Ford:\t\t {Ford.velocity}")

Refer the following Output:

Car:         3
Chryler:     3
Ford:        3
Ford velocityX:      2

Car:         4
Chryler:     4
Ford:        4

Upvotes: 1

desmaxi
desmaxi

Reputation: 291

This is because at the beginning none of the two subclasses have their velocity, they thus inherit them from the superclass. Once you set the velocity of the child class it will override the velocity for him and will not look to that of the superclass anymore.

Upvotes: 2

Basya
Basya

Reputation: 1485

You have created a new variable, named 'velocity' in Ford. If you print out the dictionary of all the variables in, for example, Ford and Chrysler, you will see that they are different:

    >>> print(Ford)
    <class '__main__.Ford'>
    >>> print (Ford.__dict__)
    {'__module__': '__main__', '__doc__': None, 'velocity': 2}
    >>> print (Chrysler.__dict__)
    {'__module__': '__main__', '__doc__': None}

From here on, if you access 'velocity' in Ford, you will get the one in Ford's dictionary, not the one in the base class.

Upvotes: 2

Related Questions