属性中我们学习一种叫私有化属性,方法中也有私有化方法,下面就来看看私有化方法的定义和使用,同时比较一下私有化方法和私有化属性在内存中的存储机制。
1.私有化方法定义
私有化方法和私有属性的定义语法是一样的,使用双下划线来命名就可以了。
class Dog(object):
__name = 'Tom'
def eat(self):
print('Tom在吃东西')
def __run(self):
return 'Tom在跑步'
私有化方法和私有化属性的本质是相同的,不同之处是表现在内存中存储的数据不一样,一个是值,一个是方法。
2.私有化方法使用
我们使用类名和对象名分别调用私有化方法试试。
d = Dog() # 实例化一个对象
print(Dog.__name) # 使用类名调用私有属性
Dog.__run(d) # 使用类名调用私有方法
d.eat() # 使用对象调用类方法
d.__run() # 使用对象调用私有方法
返回结果:
AttributeError: 'Dog' object has no attribute '__name'
AttributeError: type object 'Dog' has no attribute '__run'
AttributeError: 'Dog' object has no attribute '__eat'
我们发现不论是类名直接调用私有方法还是实例调用都会报错,下面通过__dict__内置属性来探索一下。
3.私有化方法内存存储机制
首先看看私有方法在内存中是不是和私有属性一样被重命名了。
print(Dog.__dict__)
返回结果:
{'__module__': '__main__', '_Dog__name': 'Tom', 'eat': <function Dog.eat at 0x0000000002352280>, '_Dog__run': <function Dog.__run at 0x00000000023523A0>, '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}
我们发现私有属性和方法都被重命名了:'_Dog__name': 'Tom','_Dog__run': <function Dog.__run at 0x00000000023523A0>,
回过头我们再用对象和类名来调用重命名的方法。
print(Dog._Dog__run(d))
print(d._Dog__run())
返回结果:
Tom在跑步
Tom在跑步