我有一个类(bot),它有一个属性"health";因为这个类有很多参数,我希望用户输入很多参数,所以我选择循环遍历一个{ param :explanation}的dict,并为每个参数输入一个要设置的值。
attr_array = ["health",...]
attr_dict = {}
attr_dict["health"] = "your bot's health"
...
for attr in attr_array:
tmp_attr = input(attr + attr_dict[attr] + ": ")
setattr(tmp_bot, attr_dict[attr], tmp_attr)
print attr, getattr(tmp_bot, attr_dict[attr])
print str(tmp_bot.health) + " hp"
So, the print attr, getattr... line returns (sample) "health 50"
However, the print str line returns "0 hp"
Is there any reason for this to happen?发布于 2011-03-13 01:37:18
问题评论:你为什么要这样做?
setattr(tmp_bot, attr_dict[attr], tmp_attr)而不是
setattr(tmp_bot, attr, tmp_attr)我想真正的问题是,当一个访问属性“你的机器人的健康”,另一个访问属性“健康”时,为什么你期望这两个打印行输出相同的结果。
另一个建议:您应该将健康元素定义为全局字符串(例如,如attr_arr = " HEALTH ")。这样,您仍然可以打印它们,并键入它们,依此类推,但如果您意外地在某个地方键入HEATH,python会抱怨一个未定义的全局变量,而不是稍后神秘地失败。
https://stackoverflow.com/questions/5281297
复制相似问题