'How do i call a class method using the globals() function?
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.
Solution 1:[1]
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")()
Solution 2:[2]
This would work:
class Test:
def func1():
print("test working")
Test.func1()
This runs the function func1() and produces the result.
output:
test working
Solution 3:[3]
class test():
def func1():
print ("test")
eval("test.func1()")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | S.B |
| Solution 3 | gnight |
