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!

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.