<分区>
Possible Duplicate:
Calling a function from a string with the function's name in Python
我认为我可以编写一些糟糕的代码来执行此操作,但我更愿意看到“干净的版本”。
在我看来,好的方法是制作一个包含给定对象可以使用的各种功能的字典。然后,当用户被指示告诉对象它在做什么时,它会根据该命令吐出一个菜单。
我四处搜索了一下,并没有真正看到适合我的东西,所以我想我会试一试。好吧,它没有用。
class Man(object):
def __init__(self):
self.cmds = ['foo', 'bar']
def foo(self):
print "Foo called."
def bar(self):
print "Bar called."
def junk(self):
print "Junk called." ##not in dict, on purpose, will explain
def menu(self):
while True:
print "List of actions:"
for acts in self.cmds:
print acts
cmd = raw_input("> ")
if cmd in self.cmds:
cmd() ##doesn't work.
##neither did self.cmd() (got AttributeError, obviously)
result = getattr(self, cmd)() ## this works! thanks cdhowie
else:
pass
Stick = Man()
Stick.menu()
如果不是很明显,每当我输入 if-else 认为是 True 的内容时,程序都会给出 TypeError - 在这种情况下,输入“foo”或“bar”。 事情是这样的,我知道我可以在这里写一个长长的丑陋的 if-else 东西并使这个例子工作 - 但我希望能够从 self.cmds 中追加/删除以改变对象的功能。因此第三个函数 Junk(); Stick 无法从当前的字典菜单访问“Junk()”,但我希望通过一些 self.cmds.append 操作,它能够访问。
该死的 Python,它们是如何工作的?这是解决此问题的正确方法,还是有更简单的方法?
编辑:我的答案是在 getattr 的魔法中找到的。谢谢 cdhowie。诀窍是将 while 循环更改为具有此位:result = getattr(self, cmd)()
我现在知道我的下一个任务是最终弄清楚 getattr() 的实际作用。请原谅我的菜鸟身份,呵呵,我不知道我在写什么:)
最终编辑:虽然 cdhowie 的示例适用于原始程序,但我后来发现 ders 的答案允许我在功能上做一些我无法用 getattr(); 做的事情; ders 的解决方案使我更容易在 Man 的 init 中使用其他对象中的函数 - 我认为这称为“对象组合”,对吗?无论如何,getattr() 会将 AttributeError 从 Man 以外的任何地方添加到 self.cmds 的任何函数。或者我可以再次做奇怪的事情。但足以说明,ders FTW。