Issue
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
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")()
Answered By - SorousH Bakhtiary
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.