2014-09-02 39 views
0

考慮下面的代碼:具有雙下劃線的變量不能在課堂上使用?

def __g_fun(): 
    pass 

__a = 3 
a=3 

class Test(object): 
    def __init__(self): 
     global a,__a 
     print "locals:",locals() 
     print "global:",globals() 
     self.aa = __a 
    def fun(self): 
     return __g_fun() 


t=Test() 
t.fun() 

輸出:

locals: {'self': <__main__.Test object at 0x7f53580d50d0>} 

global: {'__g_fun': <function __g_fun at 0x7f53580c52a8>, 'a': 3, '__a': 3, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'test.py', '__package__': None, 'Test': <class '__main__.Test'>, '__name__': '__main__', '__doc__': None} 

Traceback (most recent call last): 
    File "test.py", line 19, in <module> 
    t=Test() 
    File "test.py", line 11, in __init__ 
    self.aa = __a 
NameError: global name '_Test__a' is not defined 

難道雙下劃線變量不能在課堂上使用的情況下?

回答

2

事實上 - 一類代碼中雙下劃線前綴以特殊的方式由Python編譯器處理 - 在編譯的時候,這些變量名稱錯位,包括類名作爲前綴 - 以便名稱__a班級Test內的任何地方將更改爲_Test__a。 (記住「編譯時間」對用戶來說通常是透明的,並且可以被認爲是「在程序運行時」)

這是一個特徵,意思是允許一個人擁有在一個類,而不是它的子類(不是自動形式) - 一些其他語言中由「私人」成員修飾符執行的功能。

檢查Python類文檔:https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references