0

I'm new to Python and I've searched for an answer but can't find one. Maybe I'm just asking it the wrong way...

As an example, if I have a class as follows:

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

I create a couple instances as follows and can get their attributes like this:

person1 = Person("John")
person2 = Person("Mike")
print person1.name
print person2.name

What I want to do is substitute "personX" with a variable, and this is the part I haven't figured out yet. I'd like to to use this to iterate through a list of names that map to class instances and get/set their attributes.

name1 = "person1"
print "%s".name % (name1) <--- this fails with "AttributeError: 'str' object has no attribute 'name'
zend0
  • 25
  • 2
  • Consider using a list or a map for storing the instances rather that individual variables - this way you can easily iterate over any number of those. Coming back to your original questions, `eval` could be used for getting a variable by name, but that should preferably be avoided. – Vadim Landa May 21 '15 at 12:45

3 Answers3

1

Whenever you want to create variableX where X is an incrementing number, you really want a list:

people = []
people.append(Person('John'))
people.append(Person('Mike'))

for person in people:
    print person.name

print people[0].name
deceze
  • 510,633
  • 85
  • 743
  • 889
0

Use eval() to get instance referenced by the created string this way

name1 = "person1"
print eval(name1).name
farhawa
  • 10,120
  • 16
  • 49
  • 91
0

Typically, this is considered bad practice, especially with the use of eval and exec to do so:

people = {'person1': Person('Bob'), 'person2': Person('Sam')}
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70