You should call __init__ from the parent class:

class Person(object):
    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

class Teacher(Person):
    def __init__(self, name, occupation, subject):
        Person.__init__(self, name, occupation)
        self.subject = subject
Answer from Daniel on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
Python has two built-in functions that work with inheritance: Use isinstance() to check an instance’s type: isinstance(obj, int) will be True only if obj.__class__ is int or some class derived from int.
🌐
W3Schools
w3schools.com › python › python_inheritance.asp
Python Inheritance
Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function. Python also has a super() function that will make the child class inherit all the methods and properties from its parent:
Discussions

Can child classes inherit instance variables from their parent class in Python? - Stack Overflow
In Python 2.7, do instance variables need to be manually defined in a child class, or can they be inherited directly from the parent class? E.g. class Person(object): def __init__(self, name, More on stackoverflow.com
🌐 stackoverflow.com
November 23, 2017
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
Python inherit variables from parent class - Stack Overflow
To be fair, maybe OP's question ... inheritance in C++ will do. 2018-02-23T11:42:24.123Z+00:00 ... Sorry, I did not mean the question was stupid, just that the example of what it was trying to do in python made no sense because some variables were not passed through. 2019-03-18T17:26:08.14Z+00:00 ... You could try passing a Parent instance to the Child initializer...That's probably the closest you'll get. class Parent: def ... More on stackoverflow.com
🌐 stackoverflow.com
Python object instance inheriting changes to parent class by another instance - Stack Overflow
If you define it outside of a method it is a class variable and so shared between all instances. In B if you define a constructor you'll have to explicitly call A's constructor: ... This is explained (not very clearly) in the Python tutorial. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 ...
Top answer
1 of 2
4

What you ask does not make sense:

class Parent:
    def __init__(self, eye_color, length):
        self.eye_color = str(eye_color)
        self.length = length


class Child(Parent):
    def __init__(self, gender):
        super().__init__(eye_color, length)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men")

print(x.length, x.eye_color)
print(y.gender, x.length)

In child, the parameters eye_color and length come from nowhere.

rassar example is good if you want to reuse a parent object.

You can also do the following:

class Parent:
    # def __init__(self, eye_color=(default value here), length=(default value here)):
    def __init__(self, eye_color="", length=0):
        self.eye_color = str(eye_color)
        self.length = length

OR

class Parent:
    def __init__(self, eye_color="", length=0):
        self.eye_color = str(eye_color)
        self.length = length

class Child(Parent):
    def __init__(self, gender, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men") # Work with first example of Parent
y = Child("Men", eye_color="Blue", length=2) # Work with first
y = Child("Men", "Blue", 2) # Work with second example

print(x.length, x.eye_color)
print(y.gender, y.length)
2 of 2
2

You could try passing a Parent instance to the Child initializer...That's probably the closest you'll get.

class Parent:
    def __init__(self, eye_color, length):
        self.eye_color = str(eye_color)
        self.length = length


class Child(Parent):
    def __init__(self, gender, parent):
        super().__init__(parent.eye_color, parent.length)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men", x)

print(x.length, x.eye_color)
print(y.gender, x.length)

Another thing you could do is hold a last_parent variable:

global last_parent

class Parent:
        def __init__(self, eye_color, length):
            self.eye_color = str(eye_color)
            self.length = length
            last_parent = self


class Child(Parent):
    def __init__(self, gender):
        super().__init__(last_parent.eye_color, last_parent.length)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men")

print(x.length, x.eye_color)
print(y.gender, x.length)
🌐
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 according to the con...
Find elsewhere
Top answer
1 of 8
15

I find this (encapsulation) to be the cleanest way:

class Child(object):
    def __init__(self):
        self.obj = Parent()

    def __getattr__(self, attr):
        return getattr(self.obj, attr)

This way you can use all Parent's method and your own without running into the problems of inheritance.

2 of 8
11

OK, so I didn't realize that you where happy with a static copy of the arguments until I was already halfway done with my solution. But I decided not to waste it, so here it is anyway. The difference from the other solutions is that it will actually get the attributes from the parent even if they updated.

_marker = object()

class Parent(object):

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

class Child(Parent):

    _inherited = ['x', 'y', 'z']

    def __init__(self, parent):
        self._parent = parent
        self.a = "not got from dad"

    def __getattr__(self, name, default=_marker):
        if name in self._inherited:
            # Get it from papa:
            try:
                return getattr(self._parent, name)
            except AttributeError:
                if default is _marker:
                    raise
                return default

        if name not in self.__dict__:
            raise AttributeError(name)
        return self.__dict__[name]

Now if we do this:

>>> A = Parent('gotten', 'from', 'dad')
>>> B = Child(A)
>>> print "a, b and c is", B.x, B.y, B.z
a, b and c is gotten from dad

>>> print "But x is", B.a
But x is not got from dad

>>> A.x = "updated!"
>>> print "And the child also gets", B.x
And the child also gets updated!

>>> print B.doesnotexist
Traceback (most recent call last):
  File "acq.py", line 44, in <module>
    print B.doesnotexist
  File "acq.py", line 32, in __getattr__
    raise AttributeError(name)
AttributeError: doesnotexist

For a more generic version of this, look at the http://pypi.python.org/pypi/Acquisition package. It is in fact, in some cases a bloody need solution.

🌐
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.
🌐
Dremendo
dremendo.com › python-programming-tutorial › python-inheritance
Inheritance in Python Programming | Dremendo
As the class Information already exists that can store roll and name, we will create our new class Result by inheriting all the codes from the Information class without copying and pasting the codes from the Information class into the Result class. See the complete example given below. class Information: # Creating instance variables def __init__(self): self.roll = 0 self.name = "" # Creating the instance method inputinfo def inputinfo(self): self.roll = int(input('Enter Roll No: ')) self.name = input('Enter Name: ') # Creating the instance method displayinfo def displayinfo(self): print('Roll
🌐
DigitalOcean
digitalocean.com › community › tutorials › understanding-class-inheritance-in-python-3
Understanding Class Inheritance in Python 3 | DigitalOcean
August 20, 2021 - The output shows that the object ... overriding certain aspects of those methods in our child classes. Multiple inheritance is when a class can inherit attributes and methods from more than one parent class....
🌐
GeeksforGeeks
geeksforgeeks.org › python › inheritance-in-python
Inheritance in Python - GeeksforGeeks
class Animal: def __init__(self, name): self.name = name def info(self): print("Animal name:", self.name) class Dog(Animal): def sound(self): print(self.name, "barks") d = Dog("Buddy") d.info() # Inherited method d.sound() ... Promotes code reusability by sharing attributes and methods across classes. Models real-world hierarchies like Animal -> Dog or Person -> Employee. Simplifies maintenance through centralized updates in parent classes.
Published   3 weeks ago
🌐
Codecademy
codecademy.com › forum_questions › 560afacd86f552c8a70001dd
9/11 Inheritance. Don't Child Classes inherit Parent Variables? | Codecademy
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. I guess you cannot totally get rid of the duplicate efforts needed for the method call attributes. So if you add to the parent (say add price) you have to also update the children? ... Thanks.. But why redundant Calls… ... class ElectricCar(Car): def __init__(self, model, color, mpg, battery_type): super(ElectricCar,self).__init__(model, color, mpg) self.battery_type = battery_type
Top answer
1 of 2
3

Python's method resolution order works from Left to Right. It will only call the init method of the first class(A in your case). This will give you the desired result-

class A():
def __init__(self):
    super().__init__()
    self.x = 1

# parent class B
class B():
    def __init__(self):
        super().__init__()
        self.y = 2

# parent class C
class C():
    def __init__(self):
        self.z = 3

# target class D
class D(A, B, C):
    def __init__(self):
        super().__init__()

d = D()
print(vars(d))
2 of 2
2

In Python, when a class inherits from multiple parent classes, it is called multiple inheritance. In the given code, classes A, B, and C are individual classes without any direct parent classes, but they are used as base classes for the target class D. Even though these classes don't have explicit parent classes, they still require super().init() calls in their init methods because they participate in the method resolution order (MRO) used by Python to determine the order in which the init methods of the parent classes are called.

The Method Resolution Order (MRO) is a specific order in which Python searches for methods and attributes in a class hierarchy. It is determined using the C3 linearization algorithm, which helps to resolve potential ambiguities and conflicts that may arise in multiple inheritance scenarios.

In your example, when you create an instance of class D, it inherits from classes A, B, and C. The MRO is determined in a left-to-right, depth-first manner, so it follows the order of the base classes:

MRO(D) = [D, A, B, C]

Let's break down why the super().init() calls are necessary in each class:

Class A: It has no parent classes, but it's still included in the MRO because it is part of the inheritance chain for class D. The super().init() call in class A will call the init method of class B (the next class in the MRO), which in turn will call the init method of class C. Although class A doesn't have any initialization logic of its own, it is essential to call super().init() to maintain the proper MRO and ensure that the initialization logic of the other classes is executed.

Class B: Similarly to class A, class B doesn't have any direct parent classes but participates in the MRO as part of the inheritance chain for class D. The super().init() call in class B will call the init method of class C, which is the next class in the MRO.

Class C: Class C is the last class in the MRO for class D, and it initializes the attribute z with the value 3.

Class D: Finally, when you create an instance of class D, its init method will be called, and it calls super().init() to trigger the initialization process for classes A, B, and C in the correct order based on the MRO.

As a result, when you create an instance of class D, all the init methods of classes A, B, and C are executed in the correct order, and you end up with an object that has attributes x, y, and z, each initialized with their respective values.

To summarize, even though classes A and B don't have direct parent classes, they are part of the multiple inheritance chain for class D, and the super().init() calls are needed to ensure that the proper MRO is followed, and the initialization logic of all base classes is executed correctly.

🌐
Pythonclassroom
pythonclassroom.com › classes › inheritance
Inheritance | Python Classroom
Classes called child classes or subclasses inherit methods and variables from parent classes or base classes. To tell Python that a class is a child of another class, add the name of the parent class in parentheses after the name of the new class.