Run specific method of the class defined by string
I have this sample code
class aaa:
@staticmethod
def method(self):
pass
@staticmethod
def method2(self):
pas开发者_StackOverflow中文版s
command = 'method'
Now I would like to run method of the class aaa defined by command string. How could I do this? Thank you very much.
Don't. There's rarely a reason to deal with the issues (security, cleaness, performance, arguably readability, ...) that this approach introduces. Just use command = aaa.method
.
If you have to use a string (hopefully for a good reason), you can use getattr
but you propably should use an explicit mapping specifying all valid names (this also makes the code future-proof against internal renaming/refactoring):
methods = {
'method': aaa.method,
'method2': aaa.method2,
}
methods[command]()
The case "no method for this string" can be handled like this:
method = methods.get(command)
if method is None:
... # handle error/bail out
First, delete the self
parameter of your staticmethod
s - the whole point of staticmethod
s is that they don't have a self
parameter. Then, use
method = getattr(aaa, command)
method()
or simply
getattr(aaa, command)()
to call the method named by command
.
(I only wonder why you don't simply use command = aaa.method
in the first place, but there are certainly applications where this is impossible.)
You can use getattr
to get an attribute of an object by name.
In [141]: class Foo(object):
.....: def frob(self):
.....: print "Frobbed"
.....:
.....:
In [142]: f = Foo()
In [143]: getattr(f, 'frob')
Out[143]: <bound method Foo.frob of <__main__.Foo object at 0x2374350>>
In [144]: _()
Frobbed
精彩评论