我有一个 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
阻止了我这样做,如下面的回答。谢谢大家!