Reputation: 9
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?
Upvotes: 0
Views: 533
Reputation: 10395
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.
Upvotes: 1