Python 从字典中调用方法?
我正在学习python,我正在尝试用对象制作一个程序,如果你能帮助我,我将非常高兴 我试图从字典(字典操作)调用类字符的方法(方法攻击) 问题所在的行中,Python 从字典中调用方法?,python,dictionary,Python,Dictionary,我正在学习python,我正在尝试用对象制作一个程序,如果你能帮助我,我将非常高兴 我试图从字典(字典操作)调用类字符的方法(方法攻击) 问题所在的行中,play[1]是以前创建的对象;当用户键入“攻击”时,行play[1].actions[char]()应该调用play[1]对象的方法“attack”,但它给出了一个错误,即对象play[1]没有属性“actions”。如何访问该方法 我理解了为什么play[1]。操作[char]()不起作用,但我想不出另一种方法 class Characte
play[1]
是以前创建的对象;当用户键入“攻击”时,行play[1].actions[char]()
应该调用play[1]对象的方法“attack”,但它给出了一个错误,即对象play[1]没有属性“actions”。如何访问该方法
我理解了为什么play[1]。操作[char]()
不起作用,但我想不出另一种方法
class Character:
......
def attack():
print("something")
actions={"ATTACK":attack, "DEFEND": defend, "MAGIC":magic}
[...] ##in the rest of the code play[1] is created as Character
char=input("Choose Attack, Defend or Magic\n").upper()
if char in actions:
print("ciao")
play[1].actions[char]() ##Houston, we have a problem
break
您可以使用
hasattr
和getattr
:
if hasattr(play[1], actions[char]):
getattr(play[1], actions[char])()
def dummy():
pass
getattr(play[1], actions[char], dummy)()
或者不使用hasattr:
if hasattr(play[1], actions[char]):
getattr(play[1], actions[char])()
def dummy():
pass
getattr(play[1], actions[char], dummy)()
这确保了如果
play[1]
没有方法actions[char]
actions
只是一个字典,则不会出现错误。它不是字符
类的属性。您需要的是引用作为属性的操作,从actions
字典中引用它:
getattr(play[1], actions[char])()
def-attack(self):
你能显示初始化play变量的代码吗?actions
看起来不像Character
的方法,但你想从play[1]
调用它,这是Character
的一个实例,谢谢大家!!现在它工作了!:)这是一个很好的答案,但是如果代码是Python 2,那么值得一读: