#第一层封装:定义类#第二层封装:区分内外,有些属性只能内部使用,外部不能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.__widthr1=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.__widthr1=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=addrf1=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
执行其他逻辑
来源:https://www.cnblogs.com/chenyuxia/p/12147069.html