码迷,mamicode.com
首页 > 编程语言 > 详细

Python私有属性

时间:2019-09-24 15:59:42      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:command   contain   int   现在   span   index   set   ace   dac   

1 访问类的私有属性
首先我们定义一个包含私有属性的类,尝试使用实例对象访问它

[Python] 纯文本查看 复制代码
1
2
3
4
5
6
7
8
class People(object):
 
    def __init__(self):
        self.__age = 20
 
 
people = People()
print(people.__age)


结果如下:

[Python] 纯文本查看 复制代码
1
2
3
4
Traceback (most recent call last):
  File "C:/Users/flydack/Desktop/day02/private.py", line 8, in <module>
    print(people.__age)
AttributeError: ‘People‘ object has no attribute ‘__age‘



2 为什么不能直接访问呢
无法访问私有属性的原因是:python对私有属性的名字进行了修改(重写) , 这样做的好处是:防止子类修改基类的属性或者方法. 现在,我们遍历dir( people)查看people的内置方法和属性:

[Python] 纯文本查看 复制代码
1
2
for i in dir(people):
    print(i)


结果如下:

[Python] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
_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 ‘ (_类名__属性名) ,这就是我们无法直接访问私有属性或者方法的原因,那既然我们知道了这个原因,根据修改名便可以访问它了:

[Python] 纯文本查看 复制代码
1
print(people._People__age)


结果为:
20

3 关于私有属性的忠告
知道该原理便可,请不要尝试去直接访问它 , 既然人家这么设置肯定有它这么设置的理由,切不可‘  鲁莽从事啊 ‘.

更多技术资讯可关注:gzitcast

Python私有属性

标签:command   contain   int   现在   span   index   set   ace   dac   

原文地址:https://www.cnblogs.com/heimaguangzhou/p/11578503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!