Python Lessons – 7.2 Inheritance

Python Lessons - 7.2 Inheritance

Inheritance

Inheritance provides a way to share features between different classes.

Think of different classes like Triangle, Square, Pentagon. These classes differ in some respects but also have other aspects that unite them (for example color, area, etc.).

So it could be assumed that there is a superclass that has all the characteristics that unites them all. For example, in this case you could create Figure as a superclass. In order to inherit the characteristics of a class from another class, the superclass is posed as an argument.

class Shape:
    def __init__(self,color,area):
        self.color = color
        self.area = area
    def assign(self):
        print("I am a shape")

class Triangle(Shape):
    def assign(self):
        print("I am a triangle")

class Square(Shape):
    def assign(self):
        print("I am a square")

scalene = Triangle("red",120)   
painting = Square("yellow", 16)
painting.assign()
print(painting.color)
scalene.assign()
print(scalene.color) 

As you can well see, if a method already existing in the superclass is defined in the subclass, it will be overwritten (it will not be inherited).

Inheritance is said to be indirect between classes A and C, when a class A inherits from a superclass B which in turn inherits from a superclass C.

The super() method

When it is necessary to explicitly refer to an attribute or method of a superclass, the super() method is used.

class Shape:
    def __init__(self,color,area):
        self.color = color
        self.area = area
    def assign(self):
        print("I am a shape")

class Square(Shape):
    def assign(self):
        print("I am a square")
        super().assign()

painting = Square("yellow", 16)
painting.assign()

if you run the program, you get:

>>>
I am a square
I am a shape

⇐Go to Python Lesson 7.1 – Classes

Go to Python Lesson 7.4 – Object Lifecycle ⇒

Leave a Reply