Here is an example of inheritance
class Shape:
"""Basic shape class
"""
def __init__(self, n):
self.n = n
print('this is __init__ of class Shape') # this is just to show the call of __init__
def __str__(self):
return f"Shape with {self.n} sides"
class Rectangle(Shape):
"""This class represents rectangle.
Inherits from Shape, but adds functionality to calculate perimeter
"""
def __init__(self, height, width):
# call __init__ of the parent class Shape
super().__init__(4)
self.height = height
self.width = width
print('this is __init__ of class Rectangle') # this is just to show the call of __init__
@property
def perimeter(self):
return 2 * (self.height + self.width)
def __str__(self):
return f"Rectangle {self.height} x {self.width}"
class Square(Rectangle):
"""This class represents square.
Inherits from Rectangle.
"""
def __init__(self, side):
super().__init__(side, side)
self.side = side
print('This is __init__ of class Square') # this is just to show the call of __init__
def __str__(self):
return f"Square {self.height} x {self.width}"
Here we have 3 classes - class
Shape
- very basic class, class
Rectangle
, that inherits from
Shape
and add extra functionality to return perimeter and overwrite the magic method
__str__
of the parent class, and class
Square
, that inherits from
Rectangle
, but overwrites the
__str__
method. So far this is inheritance, no instantiation whatsoever, NONE.
Let's add some more code, example of instantiation
# Examples of instantiation
# Create 2 instances of class Shape
shape = Shape(3)
shape2 = Shape(5)
print(shape)
print(shape2)
print('\n------------------\n')
# Create instance of Rectangle
rectangle = Rectangle(3, 5)
print(rectangle)
print(f'Sides: {rectangle.n}') # use attribute n, inherited from Shape
print(f'Height: {rectangle.height}')
print(f'Width: {rectangle.width}')
print(f'Perimeter: {rectangle.perimeter}')
print('\n------------------\n')
# Create instance of Square
square = Square(10)
print(square)
print(f'Sides: {square.n}') # use attribute n, inherited from Rectangle, inherited from Shape
print(f'Height: {square.height}') # use attribute height, inherited from Rectangle
print(f'Width: {square.width}') # use attribute width, inherited from Rectangle
print(f'Perimeter: {square.perimeter}') # use attribute perimeter, inherited from Rectangle
This is example of instantiation. We create 2 instances of class
Shape
and 1
Rectangle
and 1
Square
.
Now, if you run the code, the output is as follows
Output:
this is __init__ of class Shape
this is __init__ of class Shape
Shape with 3 sides
Shape with 5 sides
------------------
this is __init__ of class Shape
this is __init__ of class Rectangle
Rectangle 3 x 5
Sides: 4
Height: 3
Width: 5
Perimeter: 16
------------------
this is __init__ of class Shape
this is __init__ of class Rectangle
This is __init__ of class Square
Square 10 x 10
Sides: 4
Height: 10
Width: 10
Perimeter: 40