我如何使用 globals() 函数调用 class 方法?

How do i call a class method using the globals() function?

我正在尝试使用 globals() 函数调用 class 方法。 我知道您可以使用 globals() 调用函数,因为它适用于普通函数。 这是我拥有的代码的简单版本:

class test():
    def func1():
        print("test")

globals()["test.func1"]

这也行不通:

globals()["test"].globals()["func1"]

如何在不对其进行硬编码的情况下调用该函数。

我需要 globals() 函数,因为我事先不知道我要调用哪个函数。

class test():
    def func1():
        print ("test")

eval("test.func1()")

先获取class,再获取属性

globals()["test"].func1()

globals()["test"].__dict__['func1']()

eval("test.func1()")

这也是可以的:

class A:
    class B:
        class C:
            def func1():
                print("test")

def call_by_dot(string):
    first, *rest = string.split(".")
    obj = globals()[first]
    for i in rest:
        obj = getattr(obj, i)
    return obj

call_by_dot("A.B.C.func1")()

这可行:

class Test:
    def func1():
        print("test working")



Test.func1()

这将运行函数 func1() 并产生结果。

输出:

test working