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

Time:03-21

I'm trying to call class methods using the globals() function. I know you can call functions using globals() because it works with normal functions. This is a simple version of the code I have:

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

globals()["test.func1"]

This also doesn't work:

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

How do i make it call the function without hardcoding it.

I need the globals() function because I don't know in advance which function I am going to call.

CodePudding user response:

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

eval("test.func1()")

CodePudding user response:

This would work:

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



Test.func1()

This runs the function func1() and produces the result.

output:

test working

CodePudding user response:

First get the class, then get it's attributes.

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

or

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

or

eval("test.func1()")

This is also possible:

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")()
  • Related