首页 > 代码库 > python的私有变量解析
python的私有变量解析
在内的内部定义并使用,外部无法访问,以双下划线作为前作,定义后被python转为
_classname__变量名了
--------------------------------------------------------------------------------------
In [1]: class aa:
...: __x = 12 #私有变量_ _x
...: def px(self):
...: print ‘private __x‘, aa.__x #内部访问
...:
In [2]: a = aa()
In [3]: a.px()
private __x 12
In [4]: dir(a)
Out[4]: [‘__doc__‘, ‘__module__‘, ‘_aa__x‘, ‘px‘] # map成_classname__变量名了
In [5]: a.__x = 13#实例对象a的实例变量
In [6]: dir(a)
Out[6]: [‘__doc__‘, ‘__module__‘, ‘__x‘, ‘_aa__x‘, ‘px‘]
In [7]: print a.__x
13
In [8]:In [8]: print aa.__x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-34f87438b5b5> in <module>()
----> 1 print aa.__x
AttributeError: class aa has no attribute ‘__x‘
In [9]:
-----------------------------------------------------------
_classname__变量名了
--------------------------------------------------------------------------------------
In [1]: class aa:
...: __x = 12 #私有变量_ _x
...: def px(self):
...: print ‘private __x‘, aa.__x #内部访问
...:
In [2]: a = aa()
In [3]: a.px()
private __x 12
In [4]: dir(a)
Out[4]: [‘__doc__‘, ‘__module__‘, ‘_aa__x‘, ‘px‘] # map成_classname__变量名了
In [5]: a.__x = 13#实例对象a的实例变量
In [6]: dir(a)
Out[6]: [‘__doc__‘, ‘__module__‘, ‘__x‘, ‘_aa__x‘, ‘px‘]
In [7]: print a.__x
13
In [8]:In [8]: print aa.__x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-34f87438b5b5> in <module>()
----> 1 print aa.__x
AttributeError: class aa has no attribute ‘__x‘
In [9]:
-----------------------------------------------------------
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。