問題描述
我正在編寫一個需要訪問私有變量的裝飾器并發現了這種差異.誰能解釋一下?
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. 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.
我無法重現您的示例,至少不能在 Mac 上的 Python 版本 2.4、2.5、2.6、3.1 和 3.2 中重現:
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'
如果你反匯編函數字節碼,你可以看到名字也被破壞了:
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
我檢查了 編譯器源代碼 和 所有名稱都通過 mangler 運行,這是一條至少從 2002 年以來一直保持不變的代碼路徑.
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.
是的,類屬性和實例屬性是正確的術語.類屬性始終是共享的,但是將實例上的屬性分配給 to 會分配給該實例.改變列表或其他可變對象與屬性賦值不同.
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.
這篇關于“私人"名稱修改和實例與類屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!