方法参数中的命名空间

2024-05-16 13:12:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我很惊讶方法中函数参数的命名空间是类而不是全局范围。你知道吗

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()?你知道吗


Tags: the方法testselfdef空间函数参数call
1条回答
网友
1楼 · 发布于 2024-05-16 13:12:51

命名空间查找总是首先检查本地范围。在方法定义中,就是类。你知道吗

在定义Test.a时,没有名为a的局部,只有全局a。在定义Test.b时,已经定义了Test.a,因此本地名称a存在,并且不检查全局范围。你知道吗

如果要将Test.b中的f指向全局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

一如预期。你知道吗

相关问题 更多 >