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.

Answer from user395760 on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_inheritance.asp
Python Inheritance
If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ยท If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com ยท HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ classes.html
9. Classes โ€” Python 3.14.3 documentation
It is a mixture of the class mechanisms ... mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name....
Discussions

Inherited class variable modification in Python - Stack Overflow
I'd like to have a child class modify a class variable that it inherits from its parent. I would like to do something along the lines of: class Parent(object): foobar = ["hello"] class Child( More on stackoverflow.com
๐ŸŒ stackoverflow.com
Confused about class variables, also with inheritance
The class variables and instance variables remain separate if an instance variable of the same name is created. One doesn't override the other, but the class variable will no longer be readable via the object: In [1]: class c: ...: a = 1 ...: def __init__(self): ...: self.a = 2 ...: In [2]: obj = c() In [3]: c.a Out[3]: 1 In [4]: obj.a Out[4]: 2 As for inheritance, yes if you assign a value to a class variable on a child that has the same name as one of the parent's class variables, then a separate class variable of that name will be created for the child. Again, the two will remain separate, one readable from the parent and one readable from the child, but the parent's variable will no longer be visible via the child class. More on reddit.com
๐ŸŒ r/learnpython
10
17
February 24, 2024
How does inheritance of class variables work in Python? - Stack Overflow
modifying the class variable of the supperclass Cat would normally affect every subclass that inherits the variable as well No it wouldn't. More on stackoverflow.com
๐ŸŒ stackoverflow.com
why are class variables not inherited but class methods are??
There seem to be some points of confusion on terminology here, first of all. self.goal, self.age, self.name are instance attributes, i.e. they belong to a particular instance of the class, as opposed to class attributes that belong to the class itself. print_var, print_method, and __init__ are instance methods, i.e. methods meant to use or change the attributes of a particular instance of the class, as opposed to class methods that are meant to use or change the attributes of the class itself. Now onto how OOP works in Python. The only thing a subclass inherits are its parent's class attributes. Instance methods are inherited because instance methods (like all kinds of method) are class attributes. They are dynamically bound to a particular instance only when you do an attribute look-up for the method on that instance. You also don't declare attributes (or other kinds of variable) in Python, you simply set them. Different instances of the same class can have different attributes, technically. It depends what attributes have been set on them by the code thus far: inst1 = E(...) inst2 = E(...) # This is allowed: inst1.an_attribute = 1 inst2.another_attribute = 2 So there's no way to know, from the class alone, what attributes should be there, and so that information can also not be inherited like it would in some other languages. But even in those other languages, you would still need to define somehow what values should be assigned to those inherited attributes, for example by calling the parent's constructor. Similarly, in Python, if you want to initialize an instance using the logic of a parent class, you'll have to call that parent's __init__ method, so it can set the corresponding attributes. More on reddit.com
๐ŸŒ r/learnpython
2
0
January 24, 2023
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ fopp โ€บ Inheritance โ€บ inheritVarsAndMethods.html
22.2. Inheriting Variables and Methods โ€” Foundations of Python Programming
So if you wanted to define a Dog class as a special kind of Pet, you would say that the Dog type inherits from the Pet type. In the definition of the inherited class, you only need to specify the methods and instance variables that are different from the parent class (the parent class, or the superclass, is what we may call the class that is inherited from.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ inheritance-in-python
Inheritance in Python - GeeksforGeeks
Example: Here, a parent class Animal is created that has a method info(). Then a child classes Dog is created that inherit from Animal and add their own behavior.
Published ย  2 weeks ago
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ confused about class variables, also with inheritance
r/learnpython on Reddit: Confused about class variables, also with inheritance
February 24, 2024 -

I'm finding class variables super confusing. I thought they were just like static variables in C++ (which instances can't own), but it seems they have quite different behavior.

Basic Class variable behavior - is this correct?

class Foo:
  x: int
  • if you set Foo.x, it overrides the value of .x for all instances of Foo, but

  • if you set .x on an instance of Foo, it only changes .x on that instance.

edit: actually this can't be the full story, because sometimes changing Foo.x doesn't change the instance's .x??

Class variables + inheritance, what is going on?

class Parent:
  x: int

class Child(Parent):
  pass

Parent.x = 1      
print(Child.x)        # = 1. ok so child inherits parent class variable

Child.x = 2
print(Parent.x)       # = 1. ok, so child cannot set parent class variable

Parent.x = 3
print(Child.x)         # = 2. hol' up, now child doesn't inherit from parent anymore?

Also, if multiple classes inherit from Parent, if I set Child1.x does it affect the other children? How are instances affected too?

Class variables without declaration works too...?

What's the point of defining these variables in the class body if you don't need to?

class Foo:
   pass

Foo.x = 3

I feel like there's some kind of mental model for class variables I'm just not understanding. Is there any easy way to think about them? Also is there any other weird behavior I should know?

Top answer
1 of 5
5
The class variables and instance variables remain separate if an instance variable of the same name is created. One doesn't override the other, but the class variable will no longer be readable via the object: In [1]: class c: ...: a = 1 ...: def __init__(self): ...: self.a = 2 ...: In [2]: obj = c() In [3]: c.a Out[3]: 1 In [4]: obj.a Out[4]: 2 As for inheritance, yes if you assign a value to a class variable on a child that has the same name as one of the parent's class variables, then a separate class variable of that name will be created for the child. Again, the two will remain separate, one readable from the parent and one readable from the child, but the parent's variable will no longer be visible via the child class.
2 of 5
4
If you do an attribute lookup on an instance and the attribute isn't found on the instance itself, it will look on the class next. If you do an attribute lookup on a class and it isn't found on the class itself, it will look on the parent class next. If you do an attribute assignment, however, that always sets the attribute directly on the thing itself. That means, if you do an attribute assignment on an instance, even if its class already has an attribute of that name, you create a new instance attribute rather than reassigning the class attribute. Importantly, a lookup of that attribute on the instance would now no longer propagate up to the class. The same is true for classes and their parent classes. This becomes clearer if you take a look at the special __dict__ attribute of your classes and objects as you do the assignments, which holds all direct attributes of the object or class in dictionary form.
Top answer
1 of 2
3

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
2 of 2
2

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.

Find elsewhere
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python object-oriented programming (oop) โ€บ python class variables
Python Class Variables With Examples โ€“ PYnative
September 8, 2023 - As you know, only one copy of the class variable will be created and shared between all objects of that class. When we use inheritance, all variables and methods of the base class are available to the child class.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-customize-inheritance-with-class-variables-452343
How to customize inheritance with class variables | LabEx
By understanding class variables, Python developers can create more efficient and organized code structures in LabEx programming environments. Inheritance allows classes to inherit attributes and methods from parent classes.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ why are class variables not inherited but class methods are??
r/learnpython on Reddit: why are class variables not inherited but class methods are??
January 24, 2023 -

This is my understanding as of now. Correct me if I'm wrong.

class E(A, C):
    def __init__(self, age, name, goal):
        A.__init__(self, age)   # this is just to inherit VARIABLES of A
        C.__init__(self, name)  # this is just to inherit VARIABLES of C
        self.goal = goal
    
    def print_var(self):
        print("age:", self.age)
        print("name:", self.name)
        print("goal:", self.goal)
    
    def print_method(self):
        self.printa()   # no need to write "A.__init__(self, age)" to inherit this method
        self.printc()   # methods are inherited the moment you wrote E(A, C)

Here, I had to declare that I want class A and C's variables to print it. But the print_method method worked just fine without it. Any reason why it is like that? (printa and printc just prints the statement that "this is class A/C")

Shouldn't inheritance itself mean that they will INHERITE stuff? why we need to declare it again??

Top answer
1 of 1
4
There seem to be some points of confusion on terminology here, first of all. self.goal, self.age, self.name are instance attributes, i.e. they belong to a particular instance of the class, as opposed to class attributes that belong to the class itself. print_var, print_method, and __init__ are instance methods, i.e. methods meant to use or change the attributes of a particular instance of the class, as opposed to class methods that are meant to use or change the attributes of the class itself. Now onto how OOP works in Python. The only thing a subclass inherits are its parent's class attributes. Instance methods are inherited because instance methods (like all kinds of method) are class attributes. They are dynamically bound to a particular instance only when you do an attribute look-up for the method on that instance. You also don't declare attributes (or other kinds of variable) in Python, you simply set them. Different instances of the same class can have different attributes, technically. It depends what attributes have been set on them by the code thus far: inst1 = E(...) inst2 = E(...) # This is allowed: inst1.an_attribute = 1 inst2.another_attribute = 2 So there's no way to know, from the class alone, what attributes should be there, and so that information can also not be inherited like it would in some other languages. But even in those other languages, you would still need to define somehow what values should be assigned to those inherited attributes, for example by calling the parent's constructor. Similarly, in Python, if you want to initialize an instance using the logic of a parent class, you'll have to call that parent's __init__ method, so it can set the corresponding attributes.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-30898.html
Can we access instance variable of parent class in child class using inheritance
I am pasting my code below:- class A: def __init__(self,i=100): self.i=100 class B(A): def __init__(self,j=0): self.j=j b=B() print(b.j) print(b.i)I have 2 class A and B . B is inheriting class A so a
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Define class variable in subclass - Python Help - Discussions on Python.org
April 12, 2021 - Hi all Iโ€™m trying to make a subclass inheriting from a superclass. I have a class variable that should be implemented by the subclass. My code looks like this: class mybaseclass: def hello(self): print(myclassvar) โ€ฆ
๐ŸŒ
Python
pythonprogramminglanguage.com โ€บ inheritance
Understanding Class Inheritance in Python - Python
A class can inherit the methods and variables from another class. This principle helps us to avoid duplicate code. In turn, a created object has methods and variables from both classes. Related course: Python Programming Courses & Exercises
๐ŸŒ
Codecademy
codecademy.com โ€บ forum_questions โ€บ 560afacd86f552c8a70001dd
9/11 Inheritance. Don't Child Classes inherit Parent Variables? | Codecademy
%(self.color, self.model, str(self.mpg))) def drive_car(self): self.condition = "used" my_car = Car("DeLorean", "silver", 88) print (my_car.condition) my_car.drive_car() print (my_car.condition) class ElectricCar(Car): def __init__(self, model, color, mpg, battery_type): Car.__init__(self, model, color, mpg) self.battery_type = battery_type my_car = ElectricCar("DeLorean", "silver", 88, "molten salt") print(my_car.battery_type) ... It seems like you got it. There is inheritance, we have to define values for it yet. thanks for sharing! ... It seems to me this way is slightly better than having to re-assign the self variables in ElectricCar and it works.
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ master class inheritance in python
Master Class Inheritance in Python | Towards Data Science
March 5, 2025 - Every time you assign a value to a variable, you are unconsciously creating an object. This object belongs to a particular class and owns particular attributes and methods. These characteristics were covered in the previous post, in which I provided a fast overview of classes in Python. But python classes arenโ€™t only limited to this aspect, but they are also characterized by inheritance...
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ python โ€บ inheritance
Python | Inheritance | Codecademy
June 19, 2025 - Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today. ... class ParentClass: # Parent class attributes and methods pass class ChildClass(ParentClass): # Child class inherits from ParentClass # Additional attributes and methods pass
Top answer
1 of 3
53

Python's scoping rules for barenames are very simple and straightforward: local namespace first, then (if any) outer functions in which the current one is nested, then globals, finally built-ins. That's all that ever happens when a barename is looked up, and there's no need to memorize or apply any complicated rules (nor is there any need for a Python compiler to enforce more complicated rules).

Any time you want a different lookup, you'll be using a qualified name, not a bare name. Qualified names are vastly more powerful because the lookup can always be delegated to the objects whose attributes can be requested, and those object can implement whatever lookup rules they need. In particular, in an instance method within a class, self.x is the way to ask the self object to look up attribute name 'x' -- and in that lookup it can delegate to classes, including the implementation of the concept of inheritance (and multiple inheritance, method resolution order, and so on).

The body of a class (as opposed to the bodies of the methods defined in a class) executes as part of the class statement, before the class object is created or its name is bound (in particular, before any of the bases have been defined as being bases -- though this latest detail can never matter when referring to barenames, anyway!-).

So, in your example, in class B, barename x is looked up with the universal rules -- is it a name bound locally? If no, is it bound in any outer function in which this scope is nested? If no, is it bound as a global or built-in? If none of the above, using the barename in question of course causes a name-error exception.

Since you want a different lookup sequence than the barename lookup rules universally enforce, then clearly you need to use a qualified name, not a barename; and a moment's reflection will clearly show that the "one obvious choice" for a qualified name to use for your purpose has to be A.x -- since that's where you want it to be looked up (the bases haven't been recorded anywhere yet at that point, after all... it will be the metaclass, normally type, that will do the bases-binding as part of its job when it gets called after the class body is done executing!-).

Some people are so keenly attached to other "magical" rules for the lookup of barenames that they just can't stand this aspect of Python (originally inspired, I believe, by Modula-3, a little known language that's very well considered in theoreticians' circles;-) -- having to write self.x in a method to specify that x must be looked up on self rather than using the universal barename rules, for example, drives such people batty.

Me, I love the simplicity and universality of the barename lookup rules, and I love using qualified names instead of barenames any time I want any other form of lookup... but then, it's not a secret that I'm madly in love with Python (I have my own grumbles -- e.g., global x as a statement always makes my skin crawl, where I'd much rather write global.x, i.e., have global be a built-in name for "the currently executing module"... I do love qualified names!-), is it?-)

2 of 3
35

In Python, the body of a class is executed in its own namespace before the class is created (after which, the members of that namespace become the members of the class). So when the interpreter reaches y = x+1, class B does not exist yet at that point and, therefore, has no parent.

For more details, see http://docs.python.org/reference/compound_stmts.html#class-definitions

Top answer
1 of 1
3

"after calling the add_header method on the first class instance (a in this case) b also got the header" Because both instances share same variable headers. headers should be instance rather than a class variable

class Base(object):
    __model__ = None
    def __init__(self):
        self.headers = []

    def add_header(self, *args):
        for h in args:
            self.headers.append(h)

    def set_header_values(self):
        for h in self.headers:
            setattr(self, h, getattr(self.__model__, h))


class ChildOne(Base):
    def __init__(self, model):
        super(ChildOne, self).__init__()
        self.__model__ = model


class ChildTwo(Base):
    def __init__(self, model):
        super(ChildTwo, self).__init__()
        self.__model__ = model


class Model(object):
    foo = 'bar'

m = Model()
a = ChildOne(m)
b = ChildTwo(m)
a.add_header('tralala')
print a.headers
print b.headers 

Output

['tralala']

[]

Additional note

Python class and instance variables cause confusions. Consider the following example:

class A:
    l =[] 

class B:
    l =[]

x = A()
y = A()
x.l.append(1)
print 'class A ', A.l, x.l, y.l

x = B()
y = B()
x.l = [1]
print 'class B ', B.l, x.l, y.l

Output

class A  [1] [1] [1]
class B  [] [1] []

Both examples use very similar looking access to data member 'l' however first example modifies the already existing class variable while second example creates a new instance variable.

In your example should you had an assignment self.headers = [...] instead of self.append(...) your output would be different.

Beside, __model__ attribute in your question has nothing to do with the problem.

๐ŸŒ
Built In
builtin.com โ€บ software-engineering-perspectives โ€บ python-inheritance
Python Class Inheritance Explained | Built In
Machine learning tools like Scikit-learn and Pandas commonly use inheritance to streamline workflows. more Python class inheritance allows child classes to reuse and extend methods and attributes from parent classes.