1

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?

zhang
  • 11
  • 1
  • 1
    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"`? – phooji Mar 12 '11 at 07:35
  • There is no good reason because that's wrong. Thank you. – zhang Mar 12 '11 at 07:37
  • Welcome. 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. – phooji Mar 12 '11 at 07:40
  • @phoo: you should make that an answer, because it is! – Katriel Mar 12 '11 at 15:19
  • @katrielalex: I suppose I could -- done :) – phooji Mar 12 '11 at 17:37

1 Answers1

1

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.

phooji
  • 10,086
  • 2
  • 38
  • 45