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):
    pass

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):
        print('hello')

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

class Manager(Employee, Person):
    pass

if __name__ == '__main__':
    john_doe = Manager()
    print(dir(john_doe)
    print(john_doe.greeting)
    john_doe.function1() 

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):
    	self.name = name
    def function1(self):
    	print('Hello')

class Employee(Person):
    def __init__(self, name, job):
    	super().__init__(name)
    	self.job = job
    def function1(self):
    	print('Hi!')

if __name__ == '__main__':
    john_doe = Employee('John Doe', 'programmer')
    print(john_doe.name)
    print(john_doe.job)
    john_doe.function1()

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 *