程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python object-oriented inheritance

編輯:Python

List of articles

  • Concept of inheritance
  • Expand the classic and new categories
  • Single inheritance
  • Multiple inheritance
  • Subclasses override methods and properties with the same name as the parent class
  • expand _mro The order
  • The subclass calls the methods and properties of the parent class with the same name
  • Multiple inheritance
  • super() Method function
    • Parent class . Method call VS super() Method
      • Parent class . Method
      • super() Method
  • Private rights
    • Define all properties and methods
    • Get and modify private property values

Concept of inheritance

Inheritance in life , Generally speaking, children inherit the property of their parents .

Expand the classic and new categories

expand 1: Classic or legacy class
Classes that do not derive from any built-in type , Call it the classic class .

class Class name :
Code
......

expand 2: The new class

class Class name (object):
Code

python Object oriented inheritance refers to the relationship between multiple classes , That is, the subclass inherits all the properties of the parent class by default .

  • Experience inheritance
# Inherit : The subclass inherits all the properties and methods of the parent class by default 
# Define parent class 
from unittest import result
class A(object):
def __init__(self) -> None:
self.num = 1
def info_print(self):
print(self.num)
# Defining subclasses Inherited parent class 
class B(A):
pass
# Create objects , Verification conclusion 
result = B()
result.info_print() # 1

stay python in , All classes inherit by default object class ,object A class is a top-level class or a base class ; Other subclasses are called derived classes .

Single inheritance

The main line of the story : A pancake and fruit teacher , I've been in the pancake industry for many years , Developed a set of exquisite techniques for spreading pancakes and fruits . Master wants to teach this skill to his only and most proud disciple .

analysis : Does the apprentice want to inherit all the master's skills ?

# 1. Master class : Properties and methods 
class Master():
def __init__(self) -> None:
self.kongfu = '[ Old recipe for pancakes and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 2. Define apprentice class , Inherit master class 
class Prentice(Master):
pass
# 3. Create objects with apprentice classes , Call instance properties and methods 
daqiu = Prentice()
print(daqiu.kongfu) # [ Old recipe for pancakes and fruit ]
daqiu.make_cake() # Application [ Old recipe for pancakes and fruit ] Make pancakes and fruit 

Multiple inheritance

Story recommendation :daqiu He is a good child who loves learning , Want to learn more pancake fruit skills , therefore , Report to class to learn pancake fruit technology .

The so-called multiple inheritance means that a class inherits more than one parent class at the same time .

# 1. Define master's class 
class Master():
def __init__(self) -> None:
self.kongfu = '[ Old recipe for pancakes and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 2. Define the classes of training schools 
class School():
def __init__(self) -> None:
self.kongfu = '[ The formula of soft egg and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 3. Apprentices inherit from master and training school 
class Prentice(School,Master):
pass
daqiu = Prentice()
print(daqiu.kongfu) # [ The formula of soft egg and fruit ]
daqiu.make_cake() # Application [ The formula of soft egg and fruit ] Make pancakes and fruit 

Conclusion : If a class inherits more than one parent class , Inherit the properties and methods with the same name of the first parent class first

Subclasses override methods and properties with the same name as the parent class

The story :daqiu After mastering the skills of master and training , A new set of pancake fruit technology with my own unique formula .

# 1. Define master's class 
class Master():
def __init__(self) -> None:
self.kongfu = '[ Old recipe for pancakes and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 2. Define the classes of training schools 
class School():
def __init__(self) -> None:
self.kongfu = '[ The formula of soft egg and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 3. The disciple created the original formula 
class Prentice(School,Master):
def __init__(self) -> None:
self.kongfu = '[ Original recipe for pancakes and fruits ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
daqiu = Prentice()
print(daqiu.kongfu) # [ Original recipe for pancakes and fruits ]
daqiu.make_cake() # Application [ Original recipe for pancakes and fruits ] Make pancakes and fruit 

Conclusion : If the child class and parent class have properties and methods with the same name , When subclasses create objects and call properties and methods , The properties and methods with the same name in the subclass are called .

expand _mro The order

Get inheritance
test :


print(Prentice.__mro__)
# (<class '__main__.Prentice'>, <class '__main__.School'>, <class '__main__.Master'>, <class 'object'>)

The subclass calls the methods and properties of the parent class with the same name

The story : Some customers like to eat ancient French pancakes , There are also some people who like soft egg pancakes .

# 1. Define master's class 
class Master():
def __init__(self) -> None:
self.kongfu = '[ Old recipe for pancakes and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 2. Define the classes of training schools 
class School():
def __init__(self) -> None:
self.kongfu = '[ The formula of soft egg and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 3. The disciple created the original formula 
class Prentice(School,Master):
def __init__(self):
self.kongfu = '[ Original recipe for pancakes and fruits ]'
def make_cake(self):
self.__init__() # After changing initialization , Use your own again , If you do not call your own initialization , Will continue to stay in the previous initialization 
print(f' Application {
self.kongfu} Make pancakes and fruit ')
def make_master_cake(self):
Master.__init__(self) # Reason for calling initialization again : Here you want to call the properties and methods of the parent class with the same name , Attribute in init Initialization position , Need to call... Again init
Master.make_cake(self) # If not self Will report a mistake 
def make_school_cake(self):
School.__init__(self)
School.make_cake(self)
# 4. The subclass calls the method of the parent class with the same name 
daqiu = Prentice()
daqiu.make_master_cake() # Application [ Old recipe for pancakes and fruit ] Make pancakes and fruit 

Multiple inheritance

The story :daqiu died of old age , Want to pass on all the technology to his apprentice .

# 1. Define master's class 
class Master():
def __init__(self) -> None:
self.kongfu = '[ Old recipe for pancakes and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 2. Define the classes of training schools 
class School():
def __init__(self) -> None:
self.kongfu = '[ The formula of soft egg and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 3. The disciple created the original formula 
class Prentice(School,Master):
def __init__(self):
self.kongfu = '[ Original recipe for pancakes and fruits ]'
def make_cake(self):
self.__init__() # After changing initialization , Use your own again , If you do not call your own initialization , Will continue to stay in the previous initialization 
print(f' Application {
self.kongfu} Make pancakes and fruit ')
def make_master_cake(self):
Master.__init__(self) # Reason for calling initialization again : Here you want to call the properties and methods of the parent class with the same name , Attribute in init Initialization position , Need to call... Again init
Master.make_cake(self) # If not self Will report a mistake 
def make_school_cake(self):
School.__init__(self)
School.make_cake(self)
# The second generation of apprentices 
class Tusun(Prentice):
pass
xiaoqiu = Tusun()
xiaoqiu.make_cake() # Application [ Original recipe for pancakes and fruits ] Make pancakes and fruit 
xiaoqiu.make_master_cake() # Application [ Old recipe for pancakes and fruit ] Make pancakes and fruit 
xiaoqiu.make_school_cake() # Application [ The formula of soft egg and fruit ] Make pancakes and fruit 

super() Method function

Call the properties and methods of the parent class .

Parent class . Method call VS super() Method

Parent class . Method

It has been written a lot , Here's a summary :

  1. If the previous class name is modified , The following subclasses also need to be modified in the parent class .
  2. The amount of code is huge , More redundant

super() Method

# 1. Define master's class 
class Master():
def __init__(self) -> None:
self.kongfu = '[ Old recipe for pancakes and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 2. Define the classes of training schools 
class School():
def __init__(self) -> None:
self.kongfu = '[ The formula of soft egg and fruit ]'
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# 3. The disciple created the original formula 
class Prentice(School,Master):
def __init__(self):
self.kongfu = '[ Original recipe for pancakes and fruits ]'
def make_cake(self):
self.__init__()
print(f' Application {
self.kongfu} Make pancakes and fruit ')
def make_master_cake(self):
Master.__init__(self)
Master.make_cake(self)
def make_school_cake(self):
School.__init__(self)
School.make_cake(self)
def make_old_cake(self):
super(Prentice,self).__init__()
super(Prentice,self).make_cake()
daqiu = Prentice()
daqiu.make_old_cake() # Application [ The formula of soft egg and fruit ] Make pancakes and fruit 

The example here is abstract , If you want to know more about , You can talk about me in private , Very willing to answer

Private rights

Define all properties and methods

stay Pyhton in , You can set private permissions for instance properties and methods , That is, set an instance property or method not to inherit from its subclasses .

The story :daqiu Pass on the technology to the apprentice at the same time , Don't want to put your money (200000000) Inherit to the apprentice , This is the time for money This instance property sets the private rights .

Setting is determined by the method of permission :
Add two underscores before the property name and method name .
Experience :

class Prentice():
def __init__(self) -> None:
self.kongfu = '[ Exclusive pancake fruit ]'
self.__money = 200000000
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
def print_info(self):
print(self.kongfu)
print(self.__money)
class Tusun(Prentice):
pass
daqiu = Prentice()
daqiu.print_info()
''' [ Exclusive pancake fruit ] 200000000 '''
xiaoqiu = Tusun()
Tusun.print_info() # Report errors 

Be careful : Properties and private methods can only be accessed and modified in the class

Get and modify private property values

stay python in , While defining the function name get_xx It is used to get by the attribute , Definition set_xx Used to modify private property values .

class Prentice():
def __init__(self) -> None:
self.kongfu = '[ Exclusive pancake fruit ]'
self.__money = 200000000
def make_cake(self):
print(f' Application {
self.kongfu} Make pancakes and fruit ')
# Call private properties 
def print_info(self):
print(self.kongfu)
print(self.__money)
# Get private properties 
def get_money(self):
return self.__money
# Modify private properties 
def set_money(self,money):
self.__money = money
class Tusun(Prentice):
pass
xiaoqiu = Tusun()
money = xiaoqiu.get_money()
print(xiaoqiu.get_money()) # 200000000
xiaoqiu.set_money(500)
print(xiaoqiu.get_money()) # 500

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved