Python. Inheritance (En)

11.4.1.4 create a class hierarchy
11.4.2.2 explain the concept of inheritance with examples

Python. Inheritance

Inheritance - the ability to use the properties and methods of the base class in a new class.

Inheritance allows you to create class hierarchies. 

For example, a rectangle and a circle are special cases of a shape, and a square is a special case of a rectangle.

To describe this hierarchy in the program, you need to specify each class and its base class, and the properties which it can have.

class Shape: # base class
    pass
class Circle(Shape): # class Circle is a special case of class Shape
    pass
class Rectangle(Shape): # class Rectangle is a special case of class Shape
    pass
class Square(Rectangle): # class Square is a special case of class Rectangle
    pass

Let's describe the methods of each class

from math import pi

class Shape:
    def describe(self): # method output name of class
        print(f"Class: {self.__class__.__name__}")

class Circle(Shape):
    def __init__(self, radius): # initialize radius of circle
        self.radius = radius
    def area(self): # method return area of Circle
        return pi * self.radius ** 2
    def perimeter(self): # method return perimeter of Circle
        return 2 * pi * self.radius

class Rectangle(Shape):
    def __init__(self, width, height): # initialize width, height of rectangle
        self.width = width
        self.height = height
    def area(self): # method return area of Rectangle
        return self.width * self.height
    def perimeter(self): # method return perimeter of Rectangle
        return 2 * (self.width + self.height)

class Square(Rectangle):
    def __init__(self, size):
        super().__init__(size, size) # calls the __init__ method of the base class

side = 5
sq = Square(side)
sq.describe()             # Class: Square
print(sq.area())          # 25
print(sq.perimeter())     # 20

Method super().__init__(args) passes arguments to the base class and calls __init__ method of the base class.


Questions:

  1. Explain the term "Inheritance".
  2. How to write class Girl based on class Pupil.
  3. How to get a string for an object that will contain the name of its class?

Exercises:


Tasks:

Task 1.

a) Create a base Animal class. Add a voice() method to it, which prints the class name of its instance.

b) Create 2 child classes: Horse and Donkey, which extend the voice() method of their parent class so that, in addition to the name of the class, it also prints the sound that a certain animal makes.

с) Write a function animals_song(*animals) that “sings” with the voices of animal objects passed into it, and give an example of how it works.

 

Категория: Programming languages | Добавил: bzfar77 (11.04.2022)
Просмотров: 458 | Теги: Python, base class, Inheritance | Рейтинг: 5.0/2
Всего комментариев: 0
avatar