当前位置:网站首页>[Basic 6] - encapsulation and inheritance of classes, objects and classes
[Basic 6] - encapsulation and inheritance of classes, objects and classes
2022-07-24 05:09:00 【terrific51】
Case study : Bank card
Write a bank card :
attribute : Name of Bank , Card number , password , full name , balance
Method : Sign in , deposit
class Card():
def __init__(self,cnum,cpwd,cname,cbalance):
self.bankName = "python Bank "
self.cnum = cnum
self.cpwd = cpwd
self.cname = cname
self.cbalance = cbalance
def login(self):
num = input(" Please enter the card number :")
pwd = input(" Please input a password :")
if num==self.cnum and pwd==self.cpwd:
print(" Verify success !")
return "ok"
else:
print(" Validation failed !")
return "no"
def deposit(self):
r=self.login()# Call other methods in the question part of the class , Use self As object name
if r=="ok":
money=float(input(" Please enter the deposit amount :"))
self.cbalance+=money
print(" Deposit success ! Deposit in ",money," element ! balance ",self.cbalance," element !")
c1=Card("1001","123"," Zhang San ",1000)
c2=Card("1002","123"," Li Si ",5000)
c2.deposit()
Please enter the card number :1002
Please input a password :123
Verify success !
Please enter the deposit amount :1500
Deposit success ! Deposit in 1500.0 element ! balance 6500.0 element !
One 、 Class encapsulation
Privatize properties or attributes in a class , Privatized properties and methods can only be called inside a class
take Above Private property self.cbalance = cbalance Change it to self.__cbalance = cbalance, The running result is :
AttributeError: ‘Card’ object has no attribute ‘__cbalance’
thus it can be seen , Yes, it is encapsulation , Become private attribute , Cannot directly access
- Encapsulation can restrict access to properties or methods
class Card():
def __init__(self,cnum,cpwd,cname,cbalance):
self.bankName = "python Bank "
self.cnum = cnum
self.cpwd = cpwd
self.cname = cname
self.__cbalance = cbalance
def login(self):
num = input(" Please enter the card number :")
pwd = input(" Please input a password :")
if num==self.cnum and pwd==self.cpwd:
print(" Verify success !")
return "ok"
else:
print(" Validation failed !")
return "no"
def showBalance(self):
# Restrict access to properties or methods
r = self.login()
if r == "ok":
print(" balance :",self.__cbalance," element !")
def deposit(self):
r=self.login()# Call other methods inside the class , Use self As object name
if r=="ok":
money=float(input(" Please enter the deposit amount :"))
self.cbalance+=money
print(" Deposit success ! Deposit in ",money," element ! balance ",self.cbalance," element !")
c1=Card("1001","123"," Zhang San ",1000)
c2=Card("1002","123"," Li Si ",5000)
c2.showBalance()
Please enter the card number :1002
Please input a password :123
Verify success !
balance : 5000 element !
- Private method
take Above Private methoddef login(self):Change it todef __login(self):, Can only be called inside a class , It can improve the security of classes
Two 、 Class inheritance
One class inherits another class , Automatically own the properties and methods of this class
Parent class – Subclass
- Parent class : Define common properties and methods in multiple classes .
- stay Python in , A parent class can have more than one subclass ;
A subclass can have more than one parent class( special )( Multiple inheritance ) - object: The ultimate parent of all classes
# Parent class : Define common properties and methods in multiple classes
# stay Python in , A parent class can have more than one subclass ; A subclass can have more than one parent class ( special )( Multiple inheritance )
#object: The ultimate parent of all classes
class Animal():
def __init__(self,color,age):
print("Animal The initialization method is called !")
self.color=color
self.age=age
def eat(self):
print(" Animals are eating !")
def run(self):
print(" Animals are running !")
class Cat(Animal):# Subclass ( Parent class )
pass
class Dog(Animal):
pass
class Bird(Animal):
def fly(self):
print(" Birds are flying !")
#------------------------------
c1=Cat(" orange ",2)
c1.eat()
b1=Bird(" orange ",2)
b1.fly()
Animal The initialization method is called !
Animals are eating !
Animal The initialization method is called !
Birds are flying !
边栏推荐
- power. The operation is in the low peak period of business. Import call will help you prepare each word
- Jiang Xingqun, senior vice president of BOE: aiot technology enables enterprise IOT transformation
- Do you want to have a robot that can make cartoon avatars in three steps?
- Globally and locally consistent image completion paper notes
- Event extraction and documentation (2019)
- Ben, reducing online importance is the same. Abnormal instance CP operation found
- Introduction and use of pycharm debugging function
- What if the notepad file is too large to open? Introduction to the solution to the phenomenon that txt files are too large to be opened
- How to solve the engine prompt alias herodb and game engine startup exceptions?
- NLP learning roadmap (mind map) is very comprehensive and clear!
猜你喜欢

Markov random field: definition, properties, maximum a posteriori probability problem, energy minimization problem

Fiddler抓包工具的使用

Want to know how a C program is compiled—— Show you the compilation of the program

Yolov7 -- brief introduction of the paper

Heavy! The 2022 China open source development blue book was officially released

Crazy God redis notes 09

熊市抄底指南
![GOM engine starts M2 prompt: [x-fkgom] has been loaded successfully. What should I do if it gets stuck?](/img/32/df602f294e009c9462d955b1819ffe.png)
GOM engine starts M2 prompt: [x-fkgom] has been loaded successfully. What should I do if it gets stuck?

The x-fkgom supporting the GOM engine key.lic is authorized to start

利用a*启发式搜索解决迷宫寻路问题
随机推荐
Smart pointer, lvalue reference, lvalue reference, lambda expression
Mysq Database Constraints
How can I open and view the bin file? Diagram of reading method of bin file backed up by router
Problems and solutions of QT (online installation package) crash in win10 installation
Codeforce:d2. remove the substring (hard version) [greedy string + subsequence]
Is it true to pay attention to official account and receive Xiaomi mobile power for free? Wechat circle of friends sends Xiaomi mobile power
mapreduce概念
Chapter III encog workbench
)的低字节来反馈给应用层或者成多种格式文档:
power. The operation is in the low peak period of business. Import call will help you prepare each word
明星逆市入局的NFT,如何能走出独立行情?
Summary of common errors in wechat applet cloud development
EMQX 简单使用
How can e-commerce projects solve the over issuance of online coupons (troubleshooting + Solutions) (glory Collection)
Quick reference manual for the strongest collation of common regular expressions (glory Collection Edition)
pso和mfpso
想知道一个C程序是如何进行编译的吗?——带你认识程序的编译
Markov random field: definition, properties, maximum a posteriori probability problem, energy minimization problem
Infineon launched the world's first TPM security chip with post quantum encryption technology for firmware update
利用a*启发式搜索解决迷宫寻路问题