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

python无私有成员变量

时间:2014-06-05 10:25:10      阅读:346      评论:0      收藏:0      [点我收藏+]

标签:python培训   python   python正则表达式   python类   python实例对象变量   

python解释器将__init__函数里的__z变量转成 _classname__z了,明白规则后外部依然可以通过实力对象来访问。

In [1]: class aa:
   ...:     def __init__(self):
   ...:         self.x = 10
   ...:         self.y = 11
   ...:         self.__z = 12
   ...:     

In [2]: a = aa()

In [3]: print a.x
10

In [4]: print a.y
11

In [5]: print a.__z
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a90abb2fd47d> in <module>()
----> 1 print a.__z

AttributeError: aa instance has no attribute '__z'

In [6]: dir(a)
Out[6]: ['__doc__', '__init__', '__module__', '_aa__z', 'x', 'y']

In [7]: print _aa.__z
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-b2d0b9a63937> in <module>()
----> 1 print _aa.__z

NameError: name '_aa' is not defined

In [8]: print _aa__z
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-80bb4dde0a55> in <module>()
----> 1 print _aa__z

NameError: name '_aa__z' is not defined

In [9]: print a._aa__z
12

In [10]: a.__z = 14

In [11]: dir(a)
Out[11]: ['__doc__', '__init__', '__module__', '__z', '_aa__z', 'x', 'y']

In [12]: print a._aa__z
12





python无私有成员变量,布布扣,bubuko.com

python无私有成员变量

标签:python培训   python   python正则表达式   python类   python实例对象变量   

原文地址:http://blog.csdn.net/jeapeducom/article/details/27496985

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