当前位置:网站首页>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)
边栏推荐
- Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
- Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress
- Webhook triggers Jenkins for sonar detection
- Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
- [database I] database overview, common commands, view the table structure of 'demo data', simple query, condition query, sorting data, data processing function (single row processing function), groupi
- (practice C language every day) pointer sorting problem
- Code Execution Vulnerability - no alphanumeric rce create_ function()
- Want to do something in production? Then try these redis commands
- 1day vulnerability pushback skills practice (3)
- National standard gb28181 protocol platform easygbs fails to start after replacing MySQL database. How to deal with it?
猜你喜欢
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
Third party login initial version
JSON string conversion in unity
Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
Recursive structure
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
Have you entered the workplace since the first 00???
Jenkins continuous integration environment construction V (Jenkins common construction triggers)
Consul of distributed service registration discovery and unified configuration management
Unity knapsack system (code to center and exchange items)
随机推荐
Li Chuang EDA learning notes IX: layers
Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress
WordPress collection WordPress hang up collection plug-in
Leetcode 110 balanced binary tree
Enhanced for loop
(column 23) typical C language problem: find the minimum common multiple and maximum common divisor of two numbers. (two solutions)
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
JVM family -- monitoring tools
Explain AI accelerator in detail: why is this the golden age of AI accelerator?
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult
Slurm view node configuration information
The difference between MCU serial communication and parallel communication and the understanding of UART
Defensive programming skills
JS object definition
MySQL backup notes
[PaddleSeg 源码阅读] PaddleSeg计算Dice
Leecode 122. Zuijia timing of buying and selling stocks ②
super_ Subclass object memory structure_ Inheritance tree traceability
Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches
Leetcode51.n queen