2016-11-30 202 views
1

當我創建了一個模塊級變量__並嘗試在類的一個方法內使用(使用global關鍵字)訪問它時,名稱發生了變形。Python全局變量__

讓我給個例子:

__test = 'asd' # module level variable with __ 


class TestClass(object): 
    def test(self): 
     global __test 
     print(__test) # trying to access this variable 


a = TestClass() 
a.test() 

解釋引發的錯誤:

NameError: name '_TestClass__test' is not defined

所以我們可以看到它試圖名稱碾壓__test_TestClass__test

我認爲name-mangling應該只用於類變量(當我用self或類名訪問它們時)。

它是一個我沒有意識到的明確定義的行爲,還是某種Python錯誤?

我測試的CPython 3.5

+0

爲什麼要創建*。* 「用'__'一個模塊級變量」? – jonrsharpe

+1

特別注意,引用文檔*「這個修改不考慮標識符的語法位置」* – jonrsharpe

+0

其實我的一個學生(我在一些初級水平上教Python)做到了這一點,我不知道爲什麼它沒有爲他工作。 – Pax0r

回答

2

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam , where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

(從the Python documentation,重點煤礦)

+0

aww我應該先檢查文檔:P – Pax0r