Python私有属性
2020-12-13 15:20
标签:command contain int 现在 span index set ace dac 1 访问类的私有属性
更多技术资讯可关注:gzitcast Python私有属性 标签:command contain int 现在 span index set ace dac 原文地址:https://www.cnblogs.com/heimaguangzhou/p/11578503.html
首先我们定义一个包含私有属性的类,尝试使用实例对象访问它
class People(object):
def __init__(self):
self.__age = 20
people = People()
print(people.__age)
结果如下:
Traceback (most recent call last): File "C:/Users/flydack/Desktop/day02/private.py", line 8, in print(people.__age)
AttributeError: ‘People‘ object has no attribute ‘__age‘
2 为什么不能直接访问呢
无法访问私有属性的原因是:python对私有属性的名字进行了修改(重写) , 这样做的好处是:防止子类修改基类的属性或者方法. 现在,我们遍历dir( people)查看people的内置方法和属性:
for i in dir(people):
print(i)
结果如下:
_People__age__class____delattr____dict____dir____doc____eq____format____ge____getattribute____gt____hash____init____init_subclass____le____lt____module____ne____new____reduce____reduce_ex____repr____setattr____sizeof____str____subclasshook____weakref__
可以看到,python内部将私有__age修改成了‘ _People__age ‘ (_类名__属性名) ,这就是我们无法直接访问私有属性或者方法的原因,那既然我们知道了这个原因,根据修改名便可以访问它了:
print(people._People__age)
结果为:
20
3 关于私有属性的忠告
知道该原理便可,请不要尝试去直接访问它 , 既然人家这么设置肯定有它这么设置的理由,切不可‘ 鲁莽从事啊 ‘.