我有一个str对象,例如:menu = 'install'.我想从这个字符串运行install方法.例如,当我打电话时,menu(some, arguments)它会打电话install(some, arguments).有没有办法做到这一点?
Sam*_*lan 110
如果它在一个类中,你可以使用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()
Run Code Online (Sandbox Code Playgroud)
或者如果它是一个功能:
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()
Run Code Online (Sandbox Code Playgroud)
con*_*dle 57
你也可以使用字典.
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)
Run Code Online (Sandbox Code Playgroud)
Hus*_*aty 35
为什么我们不能使用eval()?
def install():
print "In install"
Run Code Online (Sandbox Code Playgroud)
新方法
def installWithOptions(var1, var2):
print "In install with options " + var1 + " " + var2
Run Code Online (Sandbox Code Playgroud)
然后你调用下面的方法
method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)
Run Code Online (Sandbox Code Playgroud)
这给出了输出
In install
In install with options a b
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101061 次 |
| 最近记录: |