Inheritance of classes in Python


foreword

  When writing a class, you don't always have to start with a blank slate. When between a class to be written and another class that already existsThere is a certain inheritance relationshipwhen you canCode reuse through inheritanceThe purpose is to improve development efficiency. Here's how to implement inheritance in Python .


1. The basic grammar of inheritance

  inheritance isOne of the most important features of object-oriented programming, which originates from the process of people's understanding of the objective world, and is a common phenomenon in nature. For example, each of us inherits some physical characteristics from our grandparents and parents, but each of us is different from our parents because each of us has some characteristics that are unique to us and not reflected in our parents. . Implementing inheritance in program design, expressingThis class owns all public or protected members of the class it inherits from. In object-oriented programming,inherited classcalled the parent or base class ,new classCalled a subclass or a derived class .
  through inheritanceNot only can code reuse,Well enoughStraighten out the relationship between classes through inheritance. In Python, in the class definition statement, use a pair of parentheses on the right side of the class name to enclose the name of the base class to be inherited, so as to achieve class inheritance. The specific syntax format is as follows:

class ClassName(baseclasslist): 
	'''类的帮助信息'''  # 类文档字符串
	statement  # 类体

Parameter description :

  • ClassName : Used to specify the class name.
  • baseclasslist : used to specifybase class to inherit from, there can be more than one, and the class names are separated by commas ",". If not specified, the base class object of all Python objects will be used .
  • '''Help information of the class''' : used to specify the document string of the class. After defining the string, when creating the object of the class, after entering the class name and the left bracket "(", the information will be displayed.
  • statement : Class body, mainly composed of definition statements such as class variables (or class members), methods and attributes. If you don't think about the specific function of the class when defining the class, you can also use the pass statement directly in the class body instead.

  For example, define a fruit class Fruit (as the base class), and define a class attribute (used to save the default color of the fruit) and a harvest() method in this class, and then create a Banana class and a Grape class, both inherited from Fruit class, and finally create instances of the Banana class and the Grape class, and call the harvest() method (written in the base class), the code is as follows:

class Fruit:  # 定义水果类(基类)
    color = '绿色'  # 定义类属性
    def harvest(self, color):
        print('水果是{}的'.format(color))  # 输出的是形式参数color
        print('水果已经收获......')
        print('水果原来是{}的'.format(Fruit.color))  # 输出的是类属性color
class Banana(Fruit):  # 定义香蕉类(派生类)
    color = '黄色'
    def __init__(self):
        print('我是香蕉')
class Grape(Fruit):  # 定义葡萄类(派生类)
    color = '紫色'
    def __init__(self):
        print('我是葡萄')
banana = Banana()  # 创建类的实例(香蕉)
banana.harvest(banana.color)  # 调用基类的harvest()方法
grape = Grape()  # 创建类的实例(葡萄)
grape.harvest(grape.color)  # 调用基类的harvest()方法

  Executing the above code will display the result as shown in the figure below:

insert image description here

  It can be seen from the running results that although there is no harvest() method in the Banana class and the Grape class, PythonAllow derived classes to access base class methods


2. Method rewriting

  The members of the base class will be inherited by the derived class, when a method in the base classnot fully applicableWhen using a derived class, you need to override this method of the parent class in the derived class .
  In the example code above, the harvest() method defined in the base class will display "fruit..." no matter what the derived class is, instead of displaying the name of the fruit, as shown in the following figure:

insert image description here

If you want to give different hints for different fruits, you can override the harvest() method   in the derived class . code show as below:

class Fruit:  # 定义水果类(基类)
    color = '绿色'  # 定义类属性
    def harvest(self, color):
        print('水果是{}的'.format(color))  # 输出的是形式参数color
        print('水果已经收获......')
        print('水果原来是{}的'.format(Fruit.color))  # 输出的是类属性color
class Banana(Fruit):  # 定义香蕉类(派生类)
    color = '黄色'
    def __init__(self):
        print('我是香蕉')
    def harvest(self, color):
        print('香蕉是{}的'.format(color))  # 输出的是形式参数color
        print('香蕉已经收获......')
        print('香蕉原来是{}的'.format(Fruit.color))  # 输出的是类属性color
banana = Banana()  # 创建类的实例(香蕉)
banana.harvest(banana.color)  # 调用基类的harvest()方法

  After running the above code, the result is displayed as follows:

我是香蕉
香蕉是黄色的
香蕉已经收获......
香蕉原来是绿色的

3. Call the _ _init _ _() method of the base class in the derived class

  When defining the _ _ init _ _() method in a derived class,not automatically invokedThe _ _ init _ _() method of the base class. For example, define a Fruit class, create the class attribute color in the _ _ init _ _() method, then define a harvest() method in the Fruit class, output the value of the class attribute color in this method, and then create Class Banana class, finally create an instance of Banana class, and call the harvest() method, the code is as follows:

class Fruit:  # 定义水果类(基类)
    def __init__(self, color = '绿色'):
        Fruit.color = color  # 定义类属性
    def harvest(self):
        print('水果原来是{}的'.format(Fruit.color))  # 输出的是类属性color
class Banana(Fruit):  # 定义香蕉类(派生类)
    def __init__(self):
        print('我是香蕉')
banana = Banana()  # 创建类的实例(香蕉)
banana.harvest()  # 调用基类的harvest()方法

  After the above code is executed, the exception information shown in the figure below will be displayed.

insert image description here

  Therefore, to make the derived class call the _ _ init _ _() method of the base class to perform necessary initialization, you need to use the super() function in the derived class to call the _ _ init _ _() method of the base class. The usage format is as follows:

super()._ _init_ _([参数1, ....])

注意:如果基类的初始化方法中有参数传入,则这里需要在 _ _init_ _() 括号中写入形式参数

  After adding super()._ _ init _ _() to the above code, the code and running results are shown in the figure below:

insert image description here

Guess you like

Origin blog.csdn.net/2201_75641637/article/details/129552892