问题描述
我在写这需要访问私有变量,发现这种差异一个装饰。任何人都可以解释一下吗?
I was writing a decorator that needs to access private variables and found this discrepancy. Can anyone explain this?
(Python 2.5的)
(Python 2.5)
如预期中的类定义的属性命名重整作品:
Naming mangling works as expected for attributes defined in the class:
>>> class Tester(object):
... __foo = "hi"
>>> t = Tester()
>>> t._Tester__foo
'hi'
实例属性不工作(这是我们应该做的是正确的方式?)
Instance attributes do not work (and this is the way we are supposed to do it right?)
>>> class Tester(object):
... def __init__(self):
... self.__foo = "hi"
>>> t = Tester()
>>> t._Tester__foo
AttributeError: 'Tester' object has no attribute '_Tester__foo'
P.S。是类属性,这些正确的字?他们不是静态的,但如果你把其中的一个列表,或其他一些可变类型,它是共享的...
P.S. Is "class attribute" the right word for these? They aren't static, but if you make one of those a list, or some other mutable type, it is shared...
更新
在事实上,第二个例子中工作得很好了。这是一个硬件问题(重新启动帮助)。
In fact, second example works fine, too. It was a hardware issue (restart helped).
推荐答案
这其实是不的正确。
名称重整发生在类的创建时间;引用错位的名称的任何职能调整为好。
Name mangling takes place at class creation time; any functions that refer to mangled names are adjusted as well.
我无法重现你的榜样,至少在Python版本2.4,2.5,2.6,3.1和3.2在Mac上:
I cannot reproduce your example, at least not in Python versions 2.4, 2.5, 2.6, 3.1 and 3.2 on the Mac:
>>> class Tester(object):
... def __init__(self):
... self.__foo = "hi"
...
>>> Tester()._Tester__foo
'hi'
>>> Tester().__foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Tester' object has no attribute '__foo'
如果您拆卸功能字节code可以看到的名字已经错位,以及:
If you disassemble the function bytecode you can see the name has been mangled as well:
>>> import dis
>>> dis.dis(Tester.__init__)
3 0 LOAD_CONST 1 ('hi')
3 LOAD_FAST 0 (self)
6 STORE_ATTR 1 (_Tester__foo)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE
我检查了和所有名称是通过压榨机,自2002年以来一直保持同一个code路径至少运行。
I've checked the compiler source and all names are run through the mangler, a code path that has remained the same since 2002 at least.
是的,类属性和实例属性是正确的术语。类属性始终共享,但分配的到的上一个实例的属性分配给该实例。变异列表或其他可变对象是不一样的属性分配。
And yes, class attributes and instance attributes are the correct terms. Class attributes are always shared, but assignment to an attribute on an instance assigns to the instance. Mutating a list or other mutable objects is not the same as attribute assignment.
这篇关于Python的&QUOT;私人和QUOT;名称重整和实例VS类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!