How can I pass a function's name to a function, and then call it?
How can I pass a functions name to a function and then call it? Is it possible to do this wit开发者_JAVA百科hout using
getattribute
?How can I pass a class name to a function and then instantiate the class? I know I just could pass the instance of the class directly to the function but it is important that the class gets instantiated after calling the function.
def outer(f): # any name: function, class, any callable
return f() # class will be instantiated within the scope of the function
namespace = globals()
result = namespace[func_name]()
instance = namespace[class_name](*some_args)
You can use your own dictionary (namespace) instead of globals
.
It is unclear why do you need artificial constrains such as not passing directly function/class objects, not using getattr()
.
If you have a limited number of options your planning to use, you could set up a dictionary with string keys and values of the functions/classes.
Why not use the function and the class directly?
class A(object):
pass
def f():
pass
def g(func, cls):
func()
x = cls()
g(f, A)
精彩评论