python - Python 当本地命名空间中的某些内容具有相同名称时,如何从全局命名空间调用函数?

在 Python 中,如果本地命名空间中的某些内容具有相同的名称,如何从全局命名空间调用函数?例如在 C++ 中你会做 ::globalNamespaceFunc(); 而在 PHP 你会做 \GlobalNamespaceFunc();

def lol():
    print("outer lol")

def f():
    def lol():
        print("inner lol")
    lol(); # runs inner lol
    # how to call outer lol?

回答1

你可以使用 globals()["lol"]() 。在调用 lol lol() 之后也不需要 ;

回答2

idk 如果这是一个好的解决方案,但使用 globals() 似乎有效:

def lol():
    print("outer lol")

def f():
    def lol():
        print("inner lol")
    lol(); # runs inner lol
    # how to call outer lol?
    globals()["lol"]()

f()

印刷

inner lol
outer lol

相似文章

随机推荐

最新文章