- # 第一层封装: 定义类
- # 第二层封装: 区分内外, 有些属性只能内部使用, 外部不能
- class Name:
- __a='你是猪' #封装变量 a
- def __init__(self,name):
- self.name=name
- def get_name(self):
- print('我叫 %s' %self.name)
- n1=Name('陈宇霞')
- print(Name.__dict__) #查看类属性字典
- print(n1._Name__a) #可以通过此种方式调用__a , 没有真正的封装
- # 真正的封装: 区分内外, 给用户提供一个访问的接口函数进行调用, 内部的实现逻辑, 外部无法知晓
- class Room:
- def __init__(self,name,leng,width):
- self.name=name
- self.__leng=leng
- self.__width=width
- def get(self): #接口函数, 让外部者调用隐藏的属性
- return self.__leng * self.__width
- r1=Room('厕所',100,50)
- print(r1.get()) #外部通过调用 get 函数实现
- # 执行结果:
- {'__module__': '__main__', '_Name__a': '你是猪', '__init__': <function Name.__init__ at 0x00000232CEB08EA0>, 'get_name': <function Name.get_name at 0x00000232CEB08E18>, '__dict__': <attribute '__dict__' of 'Name' objects>, '__weakref__': <attribute '__weakref__' of 'Name' objects>, '__doc__': None}
你是猪
- 5000
- # 程序具有检测自己的功能
- class Room:
- def __init__(self,name,leng,width):
- self.name=name
- self.__leng=leng
- self.__width=width
- def get(self): #接口函数, 让外部者调用隐藏的属性
- return self.__leng * self.__width
- r1=Room('厕所',100,50)
- print(hasattr(r1,'name')) #检测实例 r1 是否有 name 这个属性
- print(getattr(r1,'name')) #获取这个实例属性的值
- setattr(r1,'name','卧室') #修改实例属性的值
- print(r1.name)
- delattr(r1,'name') #删除实例属性的值
- print(r1.__dict__)
- # 使用 hasattr 的好处
- class FTP:
- def __init__(self,addr):
- print("开始连接服务器 %s" %addr)
- self.addr=addr
- f1=FTP('1.1.1.1')
- if hasattr(FTP,'get'): #判断 FTP 是否有 get 函数
- a=getattr(FTP,'get') #有的话则获取函数地址
- a() #运行函数
- else:
- print("执行其他逻辑")
- # 执行结果:
- True
厕所
卧室
{ '_Room__leng': 100, '_Room__width': 50}
开始连接服务器 1.1.1.1
执行其他逻辑
来源: http://www.bubuko.com/infodetail-3364423.html