0

So, if you want to create an object from a class you:

class person:
    pass

myObj=person()

But what if you want to create a multitude of objects? I always getting Name error:

In [1]: class person(object):
   ...:     pass
   ...: 

In [2]: for name in [khalid, majid]:
   ...:     name=person()
   ...:     
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-425dbd385d30> in <module>()
----> 1 for name in khalid, majid:
      2     name=person()
      3 

NameError: name 'khalid' is not defined

So, why is that so?

1 Answer 1

1

This doesn't work because when you write:

for name in [khalid, majid]:

Python tries to find the names khalid and majid so the objects they reference can also be referenced by the list. But those names haven't been assigned yet, hence NameError.

The best way to do this is to create a dictionary of objects, using name strings as keys:

people = {}
for name in ["khalid", "majid"]:
    people[name] = person()

You can also make the name an instance attribute:

class Person(object): # upper case for class names is conventional

    def __init__(self, name):
        self.name = name

and/or put the objects in a list:

people = []
for name in ["khalid", "majid"]:
    people.append(Person(name))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.