Python Object Oriented Inheritance

The concept of inheritance

Inheritance in daily life generally refers to children inheriting the property of their parents.

Expand classic and modern classes

Extension 1: Classic or old-fashioned classes
A class that is not derived from any built-in built-in type is called a classic class.

class class name :
	 code 
	......

Extension 2: New Class.

class class name( object):
	 code 

Python object-oriented inheritance refers to the ownership relationship between multiple classes, where subclasses default to inheriting all properties of the parent class's methods.

  • Experience inheritance
#inherit : subclass inherits all 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)
#define subclasses to inherit parent classes 
class B(A):
pass
#create objects and verify conclusions 
result = B()
result.info_print() # 1

In Python, all classes inherit the object class by default, which is the top-level or base class; The other subclasses are called derived classes.

Uni inheritance

Main storyline: A pancake fruit teacher, who has been working in the pancake fruit industry for many years, has developed a set of exquisite techniques for spreading pancake fruits. The master wants to teach this technique to his only and most proud disciple.

Analysis: Do apprentices want to inherit all the skills of their master?.

# 1. master class : properties and methods 
class Master():
def __init__(self) -> None:
  self.kongfu = '[ ancient recipe for pancakes and fruits ]'
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 2. define the apprentice class and inherit the master class 
class Prentice(Master):
pass
# 3. create objects using apprentice classes, call instance properties and methods 
daqiu = Prentice()
print(daqiu.kongfu) # [ ancient recipe for pancakes and fruits ]
daqiu.make_cake() #apply [ ancient recipe for pancakes and fruits ] making pancakes and fruits 

Multiple Inheritance

Story recommendation: Daqiu is a good student who loves learning and wants to learn many pancake fruit techniques. Therefore, he enrolled in a class to learn pancake fruit techniques.

The so-called multiple inheritance means that a class inherits multiple parent classes simultaneously.

# 1. defining master's class 
class Master():
def __init__(self) -> None:
  self.kongfu = '[ ancient recipe for pancakes and fruits ]'
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 2. define the class of training schools 
class School():
def __init__(self) -> None:
  self.kongfu = '[ recipe for soft heart egg and fruit ]'

def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 3. the apprentice inherits the class of the master and training school 
class Prentice(School,Master):
pass
daqiu = Prentice()
print(daqiu.kongfu) # [ recipe for soft heart egg and fruit ]
daqiu.make_cake() #apply [ recipe for soft heart egg and fruit ] making pancakes and fruits 

Conclusion: If a class inherits multiple parent classes, it prioritizes inheriting the same named properties and methods of the first parent class.

Subclass override parent class methods and properties with the same name

Story: After mastering the skills of his master and training, Daqiu devoted himself to developing a new set of pancake and fruit making techniques for his unique recipe.

# 1. defining master's class 
class Master():
def __init__(self) -> None:
  self.kongfu = '[ ancient recipe for pancakes and fruits ]'
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 2. define the class of training schools 
class School():
def __init__(self) -> None:
  self.kongfu = '[ recipe for soft heart egg and fruit ]'

def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 3. original recipe created by disciple 
class Prentice(School,Master):
def __init__(self) -> None:
  self.kongfu = '[ unique recipe for pancakes and fruits ]'

def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
daqiu = Prentice()
print(daqiu.kongfu) # [ unique recipe for pancakes and fruits ]
daqiu.make_cake() #apply [ unique recipe for pancakes and fruits ] making pancakes and fruits 

Conclusion: If the subclass and parent class have the same named property and method, when the subclass creates an object to call the property and method, it will call the same named property and method within the subclass.

Expansion_MRO sequence

Obtain inheritance relationship Testing:


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

Subclass calls the same named method and property of the parent class

Story: Some customers like to eat traditional Chinese pancakes and fruits, while others like soft hearted egg pancakes and fruits.

# 1. defining master's class 
class Master():
def __init__(self) -> None:
  self.kongfu = '[ ancient recipe for pancakes and fruits ]'
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 2. define the class of training schools 
class School():
def __init__(self) -> None:
  self.kongfu = '[ recipe for soft heart egg and fruit ]'

def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 3. original recipe created by disciple 
class Prentice(School,Master):
def __init__(self):
  self.kongfu = '[ unique recipe for pancakes and fruits ]'

def make_cake(self):
  self.__init__() #after changing the initialization, use your own initialization again. if you haven't called your own initialization, it will continue to stay in the previous initialization 
  print(f'application{ self.kongfu }making pancakes and fruits')

def make_master_cake(self):
  Master.__init__(self) #reason for calling initialization again : i want to call the parent class's property and method with the same name, where the property is located init initialize position, needs to be called again init
  Master.make_cake(self) #if not added self will report an error 

def make_school_cake(self):
  School.__init__(self)
  School.make_cake(self)
# 4. subclass calls the same named method of the parent class 
daqiu = Prentice()
daqiu.make_master_cake() #apply [ ancient recipe for pancakes and fruits ] making pancakes and fruits 

Multilayer inheritance

Story: Daqiu is getting old and wants to pass on all his skills to his disciple.

# 1. defining master's class 
class Master():
def __init__(self) -> None:
  self.kongfu = '[ ancient recipe for pancakes and fruits ]'
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 2. define the class of training schools 
class School():
def __init__(self) -> None:
  self.kongfu = '[ recipe for soft heart egg and fruit ]'

def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 3. original recipe created by disciple 
class Prentice(School,Master):
def __init__(self):
  self.kongfu = '[ unique recipe for pancakes and fruits ]'

def make_cake(self):
  self.__init__() #after changing the initialization, use your own initialization again. if you haven't called your own initialization, it will continue to stay in the previous initialization 
  print(f'application{ self.kongfu }making pancakes and fruits')

def make_master_cake(self):
  Master.__init__(self) #reason for calling initialization again : i want to call the parent class's property and method with the same name, where the property is located init initialize position, needs to be called again init
  Master.make_cake(self) #if not added self will report an error 

def make_school_cake(self):
  School.__init__(self)
  School.make_cake(self)
#second generation apprentices 
class Tusun(Prentice):
pass
xiaoqiu = Tusun()
xiaoqiu.make_cake() #apply [ unique recipe for pancakes and fruits ] making pancakes and fruits 
xiaoqiu.make_master_cake() #apply [ ancient recipe for pancakes and fruits ] making pancakes and fruits 
xiaoqiu.make_school_cake() #apply [ recipe for soft heart egg and fruit ] making pancakes and fruits 

The function of the super() method

Call the properties and methods of the parent class.

Parent class. Method call VS super() method

Parent class. Method

A lot has already been written above, and here's a summary:

  1. If the previous class name is modified, the subsequent subclasses using the parent class also need to be modified.
  2. The code volume is large and relatively redundant

Super() method

# 1. defining master's class 
class Master():
def __init__(self) -> None:
  self.kongfu = '[ ancient recipe for pancakes and fruits ]'
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 2. define the class of training schools 
class School():
def __init__(self) -> None:
  self.kongfu = '[ recipe for soft heart egg and fruit ]'

def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')
# 3. original recipe created by disciple 
class Prentice(School,Master):
def __init__(self):
  self.kongfu = '[ unique recipe for pancakes and fruits ]'

def make_cake(self):
  self.__init__() 
  print(f'application{ self.kongfu }making pancakes and fruits')

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() #apply [ recipe for soft heart egg and fruit ] making pancakes and fruits 

The examples here are quite abstract. If you want to delve deeper, you can privately chat with me and I am willing to answer.

Private permissions

Define all attributes and methods

In Pyhton, private permissions can be set for instance properties and methods, which means setting a certain instance property or method not to inherit to subclasses.

Story: While Daqiu passed on his technology to his disciple, he did not want to inherit his own money (200000 million) to his disciple. At this point, he had to set private ownership for the instance property of money.

The method of setting is based on permissions:
Add two underscores before the property and method names
Experience:

class Prentice():
def __init__(self) -> None:
  self.kongfu = '[ exclusive pancake fruit ]'
  self.__money = 200000000
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')

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() #error reporting 

Note: Properties and private methods can only be accessed and modified within the class.

Get and modify private property values

In Python, the function name get_xx is defined to obtain the private property, while set_xx is defined to modify the private property value.

class Prentice():
def __init__(self) -> None:
  self.kongfu = '[ exclusive pancake fruit ]'
  self.__money = 200000000
def make_cake(self):
  print(f'application{ self.kongfu }making pancakes and fruits')

#calling 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

Related articles