【发布时间】:2012-12-26 15:17:55
【问题描述】:
我有一个 python 模块,m1。
# m1.py
class C1(object):
def __init__(self):
self.__pri = 10
self._pro = 5
self.pub = 1
然后在bpython中,
>>> import m1
>>> c = m1.C1()
>>> c.__pri
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'C1' object has no attribute '__pri'
>>> c._pro
5
>>> c.pub
1
>>> dir(c)
['_C1__pri', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_pro', 'pub']
>>> c._C1__pri
10
我认为 python 中没有私有变量的概念。我们现在如何解释这种行为?
编辑:我原本希望直接访问 c.__pri 但事实证明name mangling 阻止我这样做,如下面的回答。谢谢大家!
【问题讨论】:
-
你想从我们这里得到什么?)是的,它确实像这样工作。
-
你在这里期待什么?
-
这已被广泛记录 (docs.python.org/2/tutorial/…),请在提出此类问题之前进行一些研究。
-
@l4mpi 好吧,我做了功课并进行了研究,但很不幸错过了这一点。 @alexvassel问题显然是你如何解释这一点,更不用说它是这样工作的。那里的人们亲切地提到了
name mangling。
标签: python variables accessor private-members