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)
pablopeplo
  • 13
  • 1
  • 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']`. – Aran-Fey Feb 04 '18 at 11:57
  • Because someone may have the name `print` and you'll take years to debug why doesn't your `print` command work. – user202729 Feb 04 '18 at 11:58
  • Something like: People_dict = {} \n for name in people: \n People_dict[name] = Person(name) ? – pablopeplo Feb 04 '18 at 12:01

1 Answers1

0

this creates a list of object dynamic

obj={}
for pers in people:
    obj[pers]=Person(pers)
print(obj)
Sakhri Houssem
  • 975
  • 2
  • 16
  • 32