封装
面向对象的三大特性之一。
什么是封装?
封装指的是把属性装进一个容器
封装指的是隐藏的意思,但是这种隐藏式对外不对内的。
为何要封装
封装不是单纯意义的隐藏
封装数据属性的目的:将数据属性封装起来,类外部的使用就无法直接操作该数据属性了
需要类的内部开一个接口给使用者,类的设计者可以在这个接口之上附加任意逻辑,从而严格的控制使用者对属性的操作
封装函数属性的目的:隔离复杂度
如何封装
只需要在属性前加上__开头,该属性就会被隐藏起来,该隐藏具备的特点:
1、只是一种语法意义上的变形,即__开头的属性会在检测语法时发生变形_类名__属性名
2、这种隐藏式对外不对内,因为即__开头的属性检测语法时所有代码同一发生的变形
3、这种变形只在检测语法时发生一次,在类定义之后新增的__开头属性并不会发生变形
4、如果父类不想让子类覆盖自己的属性,可以在属性前加__开头。
封装属性
class Test: __x = 'test'#隐藏数据属性 def __test(self):#隐藏函数属性 print('test') def test(self): print(self.__x)#对内不隐藏
变形格式
t1 = Test() print(Test.__dict__)# print(t1._Test__x)#变形的格式后的属性的格式 t1.test()#在类中可调用隐藏的属性,被称之接口 """ {'__module__': '__main__', '_Test__x': 'test', '_Test__test': <function Test.__test at 0x00000000024EA730>, 'test': <function Test.test at 0x00000000024EA7B8>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None} test test """
变形发生的次数
t1.__x=1111 print(t1.__dict__) print(t1.__x) ''' {'__x': 1111} 1111 '''
父类中隐藏属性不能被子类继承
class Parent: x=11 __y =22#汇编形成为_Parent__y,所以无法继承 class Son(Parent): pass print(Son.__dict__) print(Son.x) print(Son._Parent__y)#这种形式才能被调用
封装数据的意图
#封装数据的真正意图 class People: def __init__(self,name,age): self.__name =name#隐藏数据属性 self.__age =age def show(self): print(self.__name,self.__age) def set_name(self,name):#可以在被操作之前,经过其他条件和操作 if type(name) is not str: print('格式不是str') return self.__name = name def set_age(self,age): if type(age) is not int: print('格式不是age') return self.__age = age p1=People('msj',18) p1.set_name('没时间') p1.set_age(25) p1.show()
封装功能函数的真正原因:隔离复杂度
封装函数属性的真实意图 class ATM: def __card(self): print('插卡') def __auth(self): print('用户认证') def __input(self): print('输入取款金额') def __print_bill(self): print('打印账单') def __take_money(self): print('取款') def withdraw(self): self.__card() self.__auth() self.__input() self.__print_bill() self.__take_money() a=ATM() a.withdraw()