Python封装之私有属性和私有方法
在类中的方法名和属性前之前加上双下划线,即可实现属性和方法的私有化。即外面的类无法使用。只供内部的类使用。
class Person: _psw=123 def __init__(self,name,age): self.name=name self._age=age def _getPSW(self): return self._psw def Login(self): self._getPSW() return '你的年龄%'%self._age
其原理是通过将带有双下划线的方法或属于进行了内部转换。
执行以下程序
alex=Person('alex',18)
print(alex.__dict__)
print(alex._Person__age)
返回:
{'name': 'alex', '_Person__age': 18}
18
即其内部转换成了_类名__方法名(属性名)。
直接通过这种方式可能调用私用的方法或属性,这种调用方式属于“投机倒靶”。