Talking about inheritance in Python

inherit

All classes in Python are subclasses of the object class, and object inherits from type

Inheritance is divided into interface inheritance and implementation inheritance

Interface inheritance: Use the interface name of the parent class, and the subclass overrides this method. Inherit interface classes as much as possible, implement methods in subclasses, and encourage multiple inheritance of interface classes. This follows the principle of interface isolation, which is conducive to normalized design, and multiple inheritance of abstract classes is not recommended

Implementation inheritance: The subclass does not need to implement anything. Directly using the parent class interface and implementation will enhance the coupling of the code and is not recommended.

Some details

Class inheritance will eventually be instantiated, and most of the time we use objects instead of classes. So let’s take a look at it~

Inheritance process

Inheritance is just a means of code reuse, and does not say that all the code is loaded into the space of the subclass, and the method still belongs to the parent class. As you can see in the example below, Cat.func is still Animal. A closer understanding is that func is also just func. It is only bound to the class Animal. The class can only help us find this function. The subclass passes The parent class finds this function and it is over~.

classAnimal(object):

 def func(self):print("Animal.func")classDog(Animal):

 def func(self):print('Dog.func')classCat(Animal):""" No func~ """print(Animal.func)  # <function Animal.func at 0x103f79620print(Cat.func)  # <function Animal.func at 0x103f79620print(Dog.func)  # <function Dog.func at 0x104073510

The process of instantiation

The properties and methods do not appear in the instance space during the instantiation process. They still belong to the class itself, and the object can only find them and then call them. But when modifying the properties of an object, an attribute with the same name will be created in the object's space. This is an attribute of the object. The essence of complex inheritance is the same.

classAnimal(object):

 def tell(self):print('self.name:%s Animal.name %s '%(id(self.name),id(Animal.name)))

 name ='Animal'classCat(Animal):""" No func~ """

 def tell(self):super().tell()print('self.name %s Cat.name %s '%(id(self.name),id(Cat.name)))

cat =Cat()
cat.tell()
cat.name ='django'
cat.tell()

# self.name:4473398472 Animal.name 4473398472 
# self.name 4473398472 Cat.name 4473398472 
# self.name:4474859736 Animal.name 4473398472 
# self.name 4474859736 Cat.name 4473398472

Single inheritance

The method closer to this class will override the method of the ancestors. This is called method coverage or rewriting. The principle is that Python's attribute retrieval mechanism queries from the inner namespace

classMyClass(object):"""
 A simple example class"""
 MyClassName ='MyClass'
 name ='MyClass'

 def func(self):print("This is {}".format(self.__class__.name))

 def get_name(self):print(self.name)classMySonClass(MyClass):

 MySonClass ='MySonClass'
 name ='MySonClass' #Attribute rewriting

 def get_name(self):super().get_name()print('I rewrite the get of the parent class_The name method, above is the method of the parent class, I come from the subclass!')

person1 =MyClass()
person2 =MySonClass()

person1.func()
person2.func()  #The implementation of the method inherits itself, and it will directly call the method of the parent class. But the attributes used are still their own.
print('*'*40)
person1.get_name()
person2.get_name()  #The interface of the method is inherited, and this method is overridden in the subclass.

# result
#------------------------------ 
# This is MyClass
# This is MySonClass
# ****************************************
# MyClass
# MySonClass
# I rewrite the get of the parent class_The name method, above is the method of the parent class, I come from the subclass!

Multiple inheritance

In terms of form, the inheritance list of a class can be one or multiple. When the inheritance list has only one class, that is, when there is only one parent class, it is called single inheritance, and more than one class is called multiple inheritance.

The inheritance method of modern classes is breadth first inheritance, and the inheritance method of classic classes is depth first inheritance.

The order of class inheritance can be checked using the mro method of the class.

Diamond inheritance

classA(object):
 m ='a'classB(A):
 m ='b'classC(A):
 m ='c'classD(B,C):
 # m ='d'
 pass
x =D()print(x.m)

# If an instantiated object of D gets the m attribute, it will look for its own namespace first, and the search order is D-  B -  C -  A

super() method

Syntax super (class, instantiated object). Method of the parent class

When the super() method is used inside the class, it does not even need any parameters

When the super() method is used in multiple inheritance, the execution is no longer the method of the parent class, but the method of the upper level in mro

In order to solve the problem of multiple inheritance, the initialization method is called repeatedly. (When using class name. method name)

When using the super() method to execute the method of the "parent class" (the previous class of the mro method)

# Repeated calls in diamond inheritance
# Pay attention to the search order of inheritance ~ use super()Will be executed in mro order

classGrand(object):
 def __init__(self, name):
 self.name = name
 print("class Grand ")classSonLeft(Grand):
 def __init__(self, age, name):
 self.age = age
 Grand.__init__(self, name) #Note: adjust and run and take a look
 # super().__init__(age, name)print("class SonLeft")classSonRight(Grand):
 def __init__(self, gender, name):
 self.gender = gender
 Grand.__init__(self, name) #Note: adjust and run and take a look
 # super().__init__(name)print("class SonRight")classGrandSon(SonLeft, SonRight):
 def __init__(self, name, age, gender):
 # super().__init__(age, name)
 SonLeft.__init__(self, age, name) #Note: adjust and run and take a look
 SonRight.__init__(self, gender, name) #Note: adjust and run and take a look
 self.gender = gender

grand_son =GrandSon("Monkey",18,"male")

The above is the detailed content of inheritance in Python. For more information about Python inheritance, please pay attention to other related articles on ZaLou.Cn!

Recommended Posts

Talking about inheritance in Python
Talking about strings in Python
Talking about the modules in Python
Talking about Python coroutine
Talking about Python functional programming
Talking about php calling python files
Learn about garbage collection in Python
Functions in python
Talking about Python multithreading and program lock
03. Operators in Python entry
Join function in Python
12. Network Programming in Python3
print statement in python
Concurrent requests in Python
Install python in Ubuntu
Learn about Python3 coroutine
Context management in Python
Arithmetic operators in python
Write gui in python
MongoDB usage in Python
Str string in Python
Computational Geometry in Python
Concurrent requests in Python (part 2)
Subscripts of tuples in Python
Noteworthy update points in Python 3.9
Does Python support multiple inheritance?
Containerize Python applications in 3 minutes
What is introspection in python
What is object-oriented in python
Generators and iterators in Python
The usage of wheel in python
Summary of logarithm method in Python
Use of Pandas in Python development
Use nohup command instructions in python
What is list comprehension in python
Getting started with Numpy in Python
Detailed sorting algorithm (implemented in Python)
How to wrap in python code
What does rc1 mean in python
Common errors and solutions in python
Use of numpy in Python development
What does def in python do
How to omit parentheses in Python
Detailed usage of dictionary in Python
Usage of os package in python
How to write classes in python
How to filter numbers in python
​What are the numbers in Python?
How to read Excel in Python
There are several keywords in Python
Everything in Python is an object
How to view errors in python
What does np do in python
How to write return in python
How to understand variables in Python
How to clear variables in python
The usage of tuples in python
How to use SQLite in Python
Description of in parameterization in python mysql