当前位置:网站首页>Object oriented -- encapsulation, inheritance, polymorphism
Object oriented -- encapsulation, inheritance, polymorphism
2022-07-04 03:33:00 【Naive code writing】
encapsulation :
# encapsulation
# The data ( attribute )、 Realization ( Method 、 function ) Put it inside the class to complete , Display an interface ( Functions that can be called ).
# in other words , Encapsulated classes , It's a black box .
# What do you want to do , Tell directly “ class ” A sound , Just fine , Class is automatically completed
# Compare with function , Class is a higher-level encapsulation ( More advanced functions )
# Of course , Class implements a higher level of encapsulation , It not only encapsulates the operation , It also encapsulates the data .
# such as , Construct a function show(), You can print the values of all variables . And don't care about the variable name and other specific information
# Use ,set、get Before setting , Judge the numerical logic
Construct a class , Construct a method in a class , It can display the corresponding attributes of this class .
Call directly :
class person():
def __init__(self,name,age,grade):
print("===== Start ======")
self.name=name
self.age=age
self.grade=grade
Zhang San =person(' Zhang San ',23,98)
print( Zhang San .name)
print( Zhang San .age)
print( Zhang San .grade)# It's too troublesome every time
encapsulation :
class person():
def __init__(self,name,age,grade):
print("===== Start ======")
self.name=name
self.age=age
self.grade=grade
def show(self):
print(self.name)
print(self.age)
print(self.grade)
print("===== end ======")
Zhang San =person(' Zhang San ',23,98)
Zhang San .show()# It can output directly
Li Si =person( Li Si ,24,88)
Li Si .show()
Wang Wu =person( Wang Wu ,25,66)
Wang Wu .show()
Inherit :
The child class inherits the parent class ( Base class ) Methods
Two understandings :
( From top to bottom )
Extract commonalities , Take developing games as an example :
such as , There are many different kinds of monsters in the game , No
There are many same attributes between the same monsters 、 action ( Method )
We construct a base class “ Monster ”
Put different kinds of monsters , Same property 、 Method , discharge
In the base class “ Monster ” Just inside .
( From top to bottom )
Better extension : Game recharge .
If , Coincident double 11, We can recharge in the class , increase
Add a double 11 Activities .
Meet the game anniversary , Add a discount .
The number of people online has reached 10 ten thousand , Add an event discount .
such , Increase , Recharge class , More and more big
It's troublesome to modify every time ,
Inherit , Every activity , All inherit from the base class .
class guaishou:
def shout(self):
print("AAAAAAAA")
class fei(guaishou):
def fly(self):#() Fill in the parent class , Defined jisuanji This class inherits ( contain )students Function of
print(" I can fly ....")
class shui(guaishou):
def swim(self):
print(" I swim in the water ...")
class lu(guaishou):
def run(self):
print(" Run! , brother ...")
xiaobai=guaishou()
xiaobai.shout()
feishou=fei()
feishou.shout()# You can call the function of the parent class directly ( Method )
feishou.fly()
shuishou=shui()
shuishou.shout()
shuishou.swim()
lushou=lu()
lushou.shout()
lushou.run()
Output results :
AAAAAAAA
AAAAAAAA
I can fly ....
AAAAAAAA
I swim in the water ...
AAAAAAAA
Run! , brother ...
practice :
class student():
def learn(self):
print(" Serious class ")
class jisuanji(student):#() Fill in the parent class , Defined jisuanji This class inherits ( contain )students Function of
def biancheng(self):
print(" Write good code ")
class jinrong(student):
def jinrongjiaoyi(self):
print(" Do business ")
Xiao Ming =student()
Xiao Ming .learn()
Xiaomei =jisuanji()
Xiaomei .learn()# You can call the function of the parent class directly ( Method )
Xiaomei .biancheng()
Little love =jinrong()
Little love .learn()
Little love .jinrongjiaoyi()
Output results :
Serious class
Serious class
Write good code
Serious class
Do business
polymorphic :
Reaction to the same phenomenon
Subclasses implement polymorphic methods
# Subclasses inherit the methods of the base class ( That is output ), No operation is needed to get the method of the base class ( Output )
# Subclasses execute polymorphic methods
# Construct a method that calls the base class A, Add new subclasses , This method can also be used A
practice :
• Construct a base class “ Student ” , contain “ Study ” Method .
• Construct an inheritance class “ Computer science students ”, Re implement the method “ Study ”.
• Construct an inheritance class “ Students majoring in finance ”, Re implement the method “ Study ”.
• Construct a function fun, Can call the base class “ Student ” Methods .
• Construct objects of different classes , Take it as a function fun Parameters of
class student():
def learn(self):
print(" Have a good class ")
class jisuanji(student):
def learn(self):
print(" Write good code ")
class jinrong(student):
def learn(self):
print(" Deal well ")
def fun(student):#() Inside is the class name
print("====!!!=====")
student.learn()
print("====####=====")
Xiao Ming =student()
Xiao Ming .learn()
xiaoming=jisuanji()
xiaoming.learn()
fun(xiaoming)
xiaomei=jinrong()
fun(xiaomei)
xiaomei.learn()
class meishu(student):
def learn(self):
print(" Drawing a picture ")
xiaowang=meishu()
xiaowang.learn()
fun(xiaowang)
边栏推荐
- Keepalived set the master not to recapture the VIP after fault recovery (it is invalid to solve nopreempt)
- The first spring of the new year | a full set of property management application templates are presented, and Bi construction is "out of the box"
- Want to do something in production? Then try these redis commands
- 7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
- Experience summary of the 12th Blue Bridge Cup (written for the first time)
- 2022 examination summary of quality controller - Equipment direction - general basis (quality controller) and examination questions and analysis of quality controller - Equipment direction - general b
- WordPress collection WordPress hang up collection plug-in
- [.NET + mqtt]. Mise en œuvre de la communication mqtt dans l'environnement net 6 et démonstration de code pour l'abonnement et la publication de messages bilatéraux du serveur et du client
- Leetcode 110 balanced binary tree
- Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
猜你喜欢
Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
The first spring of the new year | a full set of property management application templates are presented, and Bi construction is "out of the box"
Don't disagree, this is the most powerful "language" of the Internet
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
What kind of experience is it when the Institute earns 20000 yuan a month!
MySQL query
The difference between MCU serial communication and parallel communication and the understanding of UART
There is no need to authorize the automatic dream weaving collection plug-in for dream weaving collection
[latex] production of complex tables: excel2latex and detail adjustment
Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?
随机推荐
I stepped on a foundation pit today
System integration meets the three business needs of enterprises
[Wu Enda deep learning] beginner learning record 3 (regularization / error reduction)
Teach you how to optimize SQL
2022 examination summary of quality controller - Equipment direction - general basis (quality controller) and examination questions and analysis of quality controller - Equipment direction - general b
Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
Learning video website
MySQL backup notes
The property of judging odd or even numbers about XOR.
機器學習基礎:用 Lasso 做特征選擇
Nbear introduction and use diagram
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
What are the virtual machine software? What are their respective functions?
Contest3145 - the 37th game of 2021 freshman individual training match_ J: Eat radish
Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?
Slurm view node configuration information
Leetcode 110 balanced binary tree
Site favorites
Zigzag scan
In my spare time, I like to write some technical blogs and read some useless books. If you want to read more of my original articles, you can follow my personal wechat official account up technology c