参考:
Python: call a function from string name
在PHP开发中,有个方法叫做:call_user_function()
通过这个方法,PHP可以传入函数名字(字符串)就可以调用,那么Python呢?
当然,Python实现这个方法也很容易:
如果是调用类方法,可以这么做,通过getattr函数:
class MyClass(object): def install(self): print "In install" method_name = 'install' # set by the command line options my_cls = MyClass() method = None try: method = getattr(my_cls, method_name) except AttributeError: raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name)) method()
如果是普通方法调用,可以这么做:
def install(): print "In install" method_name = 'install' # set by the command line options possibles = globals().copy() possibles.update(locals()) method = possibles.get(method_name) if not method: raise NotImplementedError("Method %s not implemented" % method_name) method()
普通函数调用也可以这么做,通过dict来进行键值对应:
def install(): print "In install" methods = {'install': install} method_name = 'install' # set by the command line options if method_name in methods: methods[method_name]() # + argument list of course else: raise Exception("Method %s not implemented" % method_name)
文章的脚注信息由WordPress的wp-posturl插件自动生成