How can I pass a functions name to a function and then call it? Is it possible to do this without 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.
views:
163answers:
4
+6
A:
def outer(f): # any name: function, class, any callable
return f() # class will be instantiated within the scope of the function
SilentGhost
2009-11-02 10:02:13
`name` is usually a `string`. And `string` is not callable.
J.F. Sebastian
2009-11-02 10:13:28
A:
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.
mavnn
2009-11-02 10:03:20
A:
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)
unbeknown
2009-11-02 10:05:44
+1
A:
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().
J.F. Sebastian
2009-11-02 10:08:43