setattr() 未设置

发布于 2024-10-21 06:46:32 字数 564 浏览 2 评论 0原文

我有一个类(机器人),它有一个属性“健康”;由于这个类有很多参数,并且我希望用户输入很多参数,所以我选择循环遍历 {param:explanation} 的字典,并为每个参数输入一个要设置的值。

attr_array = ["health",...]

attr_dict = {} attr_dict["health"] = "你的机器人的健康状况" ...

对于 attr_array 中的 attr: tmp_attr = 输入(attr + attr_dict[attr] + ": ") setattr(tmp_bot, attr_dict[attr], tmp_attr) 打印 attr, getattr(tmp_bot, attr_dict[attr]) 打印 str(tmp_bot.health) + " hp"

So, the print attr, getattr... line returns (sample) "health 50" However, the print str line returns "0 hp"

发生这种情况有什么原因吗?

I have a class (bot), which has an attribute "health"; since there are a lot of parameters to this class, and I wished for the user to input a lot of them, I chose to loop through a dict of {param:explanation}, and for each param, input a value to set.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

翻了热茶 2024-10-28 06:46:32

从问题评论来看:你为什么这样做

 setattr(tmp_bot, attr_dict[attr], tmp_attr)

而不是

 setattr(tmp_bot, attr, tmp_attr)

我想真正的问题是,为什么当一个访问属性“你的机器人的健康状况”而另一个访问属性时,你为什么期望这两个打印行输出相同的结果正在访问属性“健康”。

另一个专业提示:您应该将 attr_arr 元素定义为全局字符串(例如,HEALTH =“health”)。这样,你仍然可以打印它们,并键入它们,等等,但如果你不小心在某个地方输入了 HEATH,Python 会抱怨未定义的全局,而不是稍后神秘地失败。

From the question comments: Why are you doing

 setattr(tmp_bot, attr_dict[attr], tmp_attr)

and not

 setattr(tmp_bot, attr, tmp_attr)

? I guess the real question is, why do you expect those two print lines to output the same when one accesses property "your bot's health" and the other is accessing property "health".

Another protip: you should define the attr_arr elements as global strings (e.g., like HEALTH = "health"). That way, you can still print them, and key on them, and so on, but if you were to accidentally type HEATH somewhere, python would complain about an undefined global rather than mysteriously failing later on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文