0

I want to create two instances of a class UserDatum - one named Chris and the other named Steve. This is a simple example, IRL my list of names is much longer. Here is the code:

class UserDatum:
    pass

users = ["Chris", "Steve"]

for user in users:
    user = UserDatum()

I want

print Chris

to output something like "<main.UserDatum instance at 0x7fe5780217e8>". What I get now is "NameError: name 'Chris' is not defined".

I am still new to Python, so I would appreciate some hand-holding ;) Thanks!

polished
  • 17
  • 5

1 Answers1

2

I would recommend making a dict rather than trying to create variables on the fly

>>> user_datums = {name : UserDatum() for name in users}
>>> user_datums
{'Chris': <__main__.UserDatum object at 0x02F32A50>,
 'Steve': <__main__.UserDatum object at 0x02F32A70>}
>>> user_datums['Chris']
<__main__.UserDatum object at 0x02F32A50>

To show how you could use this variable

class UserDatum:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return "hi my name is {}".format(self.name)

>>> user_datums = {name : UserDatum(name) for name in users}
>>> print(user_datums['Chris'])
hi my name is Chris
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Many thanks for replying! I have a couple of questions: 1) why is it better than creating variables on the fly? 3) can you please show how to create variables on the fly (if it is at all possible)? 3) can you please explain why my code does not work? Thanks again! – polished Feb 27 '15 at 13:34
  • You can use [`globals` to create variables at run time](http://stackoverflow.com/a/5036827/2296458). You can do the [same thing with `locals`](https://stackoverflow.com/questions/8028708/dynamically-set-local-variable-in-python?lq=1) but again [I would discourage that](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html). – Cory Kramer Feb 27 '15 at 13:43