2011-08-18 75 views
2

我很惊讶方法中函数参数的名称空间是类而不是全局作用域。方法参数中的命名空间

def a(x): 
    print("Global A from {}".format(x)) 

class Test: 
    def a(self, f=a): 
     print("A") 
     f("a") # this will call the global method a() 

    def b(self, f=a): 
     print("B") 
     f("b") # this will call the class method a() 

t=Test() 
t.b() 

如何解释?而我将如何从b的参数访问全局a()?

回答

2

命名空间查找总是首先检查本地作用域。在方法定义中,就是类。

Test.a的定义时,没有本地名为a,只有全球a。在定义Test.b时,Test.a已经定义,所以本地名称a存在,并且不检查全局范围。

如果你想指向Test.bf全球a,用途:

def a(x): 
    print("Global A from {}".format(x)) 

class Test: 

    def a(self, f=a): 
     print("A") 
     f("a") # this will call the global method a() 

    def b(self, f=None): 
     f = f or a 
     print("B") 
     f("b") # this will call the class method a() 

t=Test() 
t.b() 

它打印

 
B 
Global A from b 

预期。

+0

谢谢!这样可行。然而,对于我来说,参数命名空间与方法代码中的命名空间不同... – Gerenuk

+0

是的,在我习惯之前,它对我来说也是意外的。 – agf