Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherited class variable modification in Python

People also ask

Are class variables inherited in Python?

Class Variables In Inheritance We can use the parent class or child class name to change the value of a parent class's class variable in the child class. What if both child class and parent class has the same class variable name. In this case, the child class will not inherit the class variable of a base class.

How do you modify a class variable?

We should be careful when changing the value of a class variable. If we try to change a class variable using an object, a new instance (or non-static) variable for that particular object is created and this variable shadows the class variables. Below is a Python program to demonstrate the same.

Can a class inherit variables?

A class in Java can be declared as a subclass of another class using the extends keyword. A subclass inherits variables and methods from its superclass and can use them as if they were declared within the subclass itself: class Animal { float weight ; ...

Do child classes inherit variables?

We know every Child class inherits variables and methods (state and behavior) from its Parent class. Imagine if Java allows variable overriding and we change the type of a variable from int to Object in the Child class.


Assuming you want to have a separate list in the subclass, not modify the parent class's list (which seems pointless since you could just modify it in place, or put the expected values there to begin with):

class Child(Parent):
    foobar = Parent.foobar + ['world']

Note that this works independently of inheritance, which is probably a good thing.


You should not use mutable values in your class variables. Set such values on the instance instead, using the __init__() instance initializer:

class Parent(object):
    def __init__(self):
        self.foobar = ['Hello']

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()
        self.foobar.append('world')

Otherwise what happens in that the foobar list is shared among not only the instances, but with the subclasses as well.

In any case, you'll have to avoid modifying mutables of parent classes even if you do desire to share state among instances through a mutable class variable; only assignment to a name would create a new variable:

class Parent(object):
    foobar = ['Hello']

class Child(Parent):
    foobar = Parent.foobar + ['world']

where a new foobar variable is created for the Child class. By using assignment, you've created a new list instance and the Parent.foobar mutable is unaffected.

Do take care with nested mutables in such cases; use the copy module to create deep copies if necessary.