Does python have call_user_func () like PHP?
Choosing an object to instantiate is not all that difficult. A class is a first-class object and can be assigned to a variable or passed as an argument to a function.
class A(object):
def __init__( self, arg1, arg2 ):
etc.
class B(object):
def __init__( self, arg1, arg2 ):
etc.
thing_to_make = A
argList= ( some, pair )
thing_to_make( *argList )
thing_to_make = B
argList- ( another, pair )
thing_to_make( *argList )
def doSomething( class_, arg1, arg2 ):
thing= class_( arg1, arg2 )
thing.method()
print thing
Everything works nicely without too many problems. You don't need the "call_user_function" function in Python
a source to share
I see no problem if methodName
it is not a string. In this case, getattr does the job:
>>> class A:
... def func(self, a, b):
... return a + b
...
>>> a = A()
>>> getattr(a, 'func')(2, 3)
5
If is object
also a string, this will work using globals or locals (but then you might have other problems):
>>> getattr(locals()['a'], 'func')(2, 3)
5
>>> getattr(globals()['a'], 'func')(2, 3)
5
Edit : Repeat your clarification. Initialize object based on string:
>>> class A:
... def __init__(self): print('a')
...
>>> class B:
... def __init__(self): print('b')
...
>>> clsStr = 'A'
>>> myObj = locals()[clsStr]()
a
I'm not sure if this is really what you want, though ... if you have a lot of different classes, why not just do string matching?
Another edit . While the above works, you should seriously consider a solution with Ignacio Vazquez-Abrams . First, by keeping all possible classes in dict
, you avoid the weird behavior that could result from passing an invalid string argument that just matches the name of an unrelated class in the current scope.
a source to share
If you need to use classes from far away (and in fact, if you need any classes at all), your best bet is to create and use a dictionary for them:
funcs = {'Eggs': foo.Eggs, 'Spam': bar.Spam}
def call_func(func_name, *args, **kwargs):
if not func_name in funcs:
raise ValueError('Function %r not available' % (func_name,))
return funcs[func_name](*args, **kwargs)
a source to share
You can call getattr command with locals () or globals () to do something like this
# foo.method() is called if it available in global scope
getattr(globals()['foo'], 'method')(*args)
# Same thing, but for 'foo' in local scope
getattr(locals()['foo'], 'method')(*args)
See also: Diving into Python with getattr () , locals (), and globals ()
a source to share