Inheritance in Python

In an >>earlier posts<< on object-oriented programming in Python, I covered the basics of inheritance. The base class (Superclass) from which the child class inherits all its attributes and methods in the derived class declaration (Subclass) as an argument, i.e.

class Subclass(Superclass):

When a child class inherits from several base classes, it also inherits attributes and methods from those classes. However, when there are attributes or methods with the same names in two different base classes, the child class inherits this attribute or method whose class was first on the argument list in the child class definition, i.e.

class Person:
    greeting = 'Hi!'
    def function1(self):

class Employee:
    greeting = "What's up!"
    def function1(self):
    def function2(self):

class Manager(Employee, Person):

if __name__ == '__main__':
    john_doe = Manager()

As you can see from the example above, the Manager class has both methods: function1 () and function2 () and the variable greeting. The value of greeting will be What’s up! and the result of the function will be world.

When inheriting a method from a base class, we can override the code of the method (override the method) and then get a completely new functionality, or extend the functionality of the method. The init () method obtained increased functionality in the derived class, while the code of the function1 () method was overridden in the subclass, i.e.

class Person:
    def __init__(self, name): = name
    def function1(self):

class Employee(Person):
    def __init__(self, name, job):
    	self.job = job
    def function1(self):

if __name__ == '__main__':
    john_doe = Employee('John Doe', 'programmer')

The function super calls a method from the bass class, in this case init (), so that the method in the subclass uses the code from the base class and adds new functionality.

Instead of using a construction with the function super (), you can use a construction with the name of the base class, i.e.

Person.__init__(self, name)

This is especially useful when a child class inherits from several base classes and we want to use a specific method from a specific base class.

Leave a Reply

Your email address will not be published. Required fields are marked *