Learning python (12)-inheritance

table of Contents

1. Inheritance mechanism

2. The parent class rewrite

(1) super() function

(2)__slots__

(3) type() function

(4) MetaClass metaclass

3. Polymorphism


1. Inheritance mechanism

The inheritance mechanism is often used to create new classes with similar functions to existing classes, or new classes only need to add some members (attributes and methods) to the existing class, but do not want to directly copy the existing class code to the new class. class. In other words, by using the mechanism of inheritance, the reuse of classes can be easily achieved.

Let the From class inherit the Shape class, so that when the From class object calls the draw() method, the Python interpreter will first look for the method named draw in From, and if it can’t find it, it will automatically look for it in the Shape class. In this way, we only need to add a method to calculate the area in the From class. The sample code is as follows:

class Shape:
    def draw(self,content):
        print("画",content)
class Form(Shape):
    def area(self):
        #....
        print("此图形的面积为...")

In the above code, class From(Shape) means that From inherits Shape. In Python, a class that implements inheritance is called a subclass, and the inherited class is called a parent class (also called a base class or a super class). So in the above example, From is the subclass and Shape is the superclass.
When a subclass inherits a parent class, you only need to put the parent class (there can be multiple) in parentheses after the subclass when defining the subclass. The syntax format is as follows:

class Class name (parent class 1, parent class 2, ...):
       #Class definition part

Note that if the class does not explicitly specify which class it inherits from, it will inherit the object class by default (the object class is the parent class of all classes in Python, that is, it is either a direct parent class or an indirect parent class). In addition, Python's inheritance is a multiple inheritance mechanism (   same as C++ ), that is, a subclass can have multiple direct parent classes at the same time. Some readers may also have heard of the term "derivation", which means the same thing as inheritance, but it has a different perspective. In other words, inheritance is relative to the child class, that is, the child class inherits from the parent class; and the derivation is relative to the parent class, that is, the parent class derives the child class. In fact, most object-oriented programming languages ​​only support single inheritance, that is, subclasses can only have one parent class. Python supports multiple inheritance (C++ also supports multiple inheritance). Compared with single inheritance, multiple inheritance tends to make the code logic complicated and confusing. It has been controversial. It is rarely used in small and medium-sized projects. Later,  Java , C# , PHP,  etc. simply cancelled multiple inheritance.

The problem often faced with using multiple inheritance is that multiple parent classes contain class methods with the same name. In this case, Python's treatment measures are: according to the order of the parent class when the child class inherits multiple parent classes, that is, the class method in the previous parent class will override the class method of the same name in the next parent class. .

2. The parent class rewrite

The child class inherits the parent class, then the child class has all the class attributes and class methods of the parent class. Under normal circumstances, subclasses will extend some new class attributes and class methods on this basis. , We may encounter such a situation, that is, most of the class methods inherited by the subclass from the parent class are suitable for use by the subclass, but there are individual class methods that cannot be copied directly from the parent class. If Without modifying this part of the class methods, the subclass objects cannot be used. In response to this situation, we need to repeat the method of the parent class in the child class.

Rewriting, sometimes called overwriting, is a meaning that refers to modifying the internal implementation of an existing method in a class. In fact, if we override the class method inherited from the parent class in the subclass, then when the method is called from the subclass object outside the class, Python will always execute the method overridden in the subclass. A class in Python can be regarded as an independent space, and a class method is actually derived from a function in that space. If you want to call a function in the class space in the global space, you only need to note the class name when calling the function.

# coding=gbk
class child:
    def __init__(self):
      pass
    
    def behavior(self):
       print("小孩在玩!")

class person:
    def __init__(self):
      pass

    def behavior(self):
        print("这人在吃饭!")

class student1(child,person):
    pass

class student2(child,person):
   def behavior(self):
       print("这人在学习!")

LiMing = student1()
LiMing.behavior()
LiMing = student2()
LiMing.behavior()

The output is:

(1) super() function

In the construction method of the subclass, there are two ways to call the construction method of the parent class, namely:

  1. The class can be regarded as an independent space, and the instance method in it can be called from the outside of the class, just like the ordinary function, but the class name needs to be added (this method is also called the unbound method);
  2. Use the super() function. But if multiple inheritance is involved, the function can only call the constructor of the first direct parent class.

In Python 3.x, the super() function has a simpler syntax format. It is recommended that you use this format:

super().__init__(self,...)

(2)__slots__

It is very flexible to dynamically add properties or methods to class or instance objects. But at the same time, if it is used indiscriminately, it will also bring certain hidden dangers to the program, that is, the classes that have been defined in the program can be dynamically modified without any restrictions. Fortunately, Python provides the __slots__ attribute, which can prevent users from frequently adding attributes or methods to instance objects dynamically.

Note that __slots__ can only be restricted to dynamically adding properties and methods to instance objects, but cannot be restricted to dynamically adding properties and methods to classes. For dynamically added methods, __slots__ restricts the method name and does not limit the number of parameters.

(3) type() function

The type() function is a  Python  built-in function, usually used to view the specific type of a variable. In fact, there is a more advanced usage of the type() function, which is to create a custom type (that is, to create a class).

There are two grammatical formats for the type() function, which are as follows:

type(obj) ;type(name, bases, dict)

In the above two grammatical formats, the meaning and function of each parameter are:

  • The first syntax format is used to view the specific type of a variable (class object), and obj represents a variable or class object.
  • The second syntax format is used to create a class, where name represents the name of the class; bases represents a tuple, which stores the parent class of the class; dict represents a dictionary that is used to represent the attributes or methods defined in the class.

Note that the Python tuple syntax stipulates that when there is only one element in the (object,) tuple, the last comma (,) cannot be omitted. , How to determine whether the method or attribute is added to the dict dictionary? Very simple, if the value in the key-value pair is a common variable (such as "C Language Chinese Network"), it means that a class attribute has been added to the class; on the contrary, if the value is an externally defined function, it means that the class has been added An instance method.

(4) MetaClass metaclass

MetaClass metaclass is essentially a class, but its usage is different from ordinary classes. It can dynamically modify the definitions inside the class (including class attributes and class methods). It can be said that the main purpose of using metaclasses is to dynamically change the properties or methods defined in the class when the class is created. If you want to use the MetaClass metaclass to dynamically modify the internal properties or methods when creating a class, the creation process of the class will become complicated: first create the MetaClass metaclass, then use the metaclass to create the class, and finally use the instance of the class The object realizes the function.

If you want to design a class as a MetaClass metaclass, it must meet the following conditions:

  1. Must explicitly inherit from the type class;
  2. The class needs to define and implement the __new__() method, which must return an instance object of the class, because when a metaclass is used to create a class, the __new__() method will be automatically executed to modify the newly created class .

When creating a class, by marking the parent class while specifying the metaclass (in the format metaclass=元类名), when the  Python  interpreter creates this class, the __new__ method in the FirstMetaClass metaclass will be called, thereby realizing dynamic modification of the class The purpose of the attribute or class method.

3. Polymorphism

Python  is a weakly typed language, and its most obvious feature is that when variables are used, there is no need to specify specific data types for them. This leads to a situation where the same variable may be assigned to different class objects one after the other.

The polymorphic characteristics of the class must meet the following two prerequisites:

  1. Inheritance: Polymorphism must occur between the child class and the parent class;
  2. Rewrite: The subclass rewrites the method of the parent class.

Guess you like

Origin blog.csdn.net/qq_35789421/article/details/113625931
Recommended