1.对数据属性操作严格控制. (对属性的操作 selfe.__property) 属性需要打印出来.
2.隔离复杂度.(对方法的操作 self.__method)
1. 案例一.控制属性 .
class Teacher():
def __init__(self,name,age):
self.name =name
self.__age =age
print(self.name)
print(self.__age)
def tell_info(self):
# print("姓名:%s,年龄:%s" %(self.__name,self.__age))
print("姓名:{},年龄:{}".format(self.name,self.__age))
def set_info(self,name,age):
if not isinstance(name,str):
raise TypeError("姓名必须是字符串")
if not isinstance(age,int):
raise TypeError("年龄必须是整形")
self.name =name
self.__age =age
t =Teacher("egon",18)
t.tell_info()
print(t.name)
print(t.__age) #会报错,无法访问.
打印结果:
C:\Python37\pythonw.exe C:/Users/acer_NK/PycharmProjects/untitled6/99.py egon 18 姓名:egon,年龄:18 egon
2.隔离复杂度,隐藏方法.
class ATM:
def __card(self):
print("插卡")
def __auth(self):
print("用户认证")
def __input(self):
print("输入金额")
def __print_bill(self):
print(‘打印金额‘)
def withdraw(self):
self.__card()
self.__auth()
self.__input()
self.__print_bill()
a =ATM()
a.withdraw()
C:\Python37\pythonw.exe C:/Users/acer_NK/PycharmProjects/untitled6/88.py 插卡 用户认证 输入金额 打印金额
原文:https://www.cnblogs.com/mengbin0546/p/10269549.html