0

Let's suppose I have a list of strings:

people = ['Mike','Paul','Caroline']

and a class:

class Person:
    def __init__(self, name, is_married = False):
        self.name = name
        self.is_married =is_married

How can i iterate through the strings in the list, and for each string create an instance of Person? Ideally, I would like to be able to call each instance through their name (the string), for example:

Mike.is_married = True
print(Mike.is_married)
3
  • 2
    "Ideally, I would like to be able to call each instance through their name" No, no, you really don't want that. Store them in a dict instead and access them as your_dict['Mike']. Commented Feb 4, 2018 at 11:57
  • Because someone may have the name print and you'll take years to debug why doesn't your print command work. Commented Feb 4, 2018 at 11:58
  • Something like: People_dict = {} \n for name in people: \n People_dict[name] = Person(name) ? Commented Feb 4, 2018 at 12:01

1 Answer 1

0

this creates a list of object dynamic

obj={}
for pers in people:
    obj[pers]=Person(pers)
print(obj)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.