Omid
Omid

Reputation: 2667

How to create and store objects of a class in a list

I need to create instances from a single class and store the names in a list.

robot_list = []
for i in range (num_robots):
    robot_list.append('robot%s' %i)

This creates a list of the names I want to use as instances of a single class Robot. But they are of the str type so far. So I wrote this to change their type and assign the instances of the class to the names:

for i in robot_list:
    i = Robot()

Later when I want to use any of the elements in the list the program returns an AttributeError saying that the object is still a string.

How can I fix this?

Upvotes: 0

Views: 194

Answers (3)

msvalkon
msvalkon

Reputation: 12077

To add to other answers: your assignment does not work the way you expect it to.

for i in robots_list:
    i = Robot()

Will not save a robot object to each index in the list. It will create the object but instead of saving it to the index you wish, it will overwrite the temporary variable i. Thus all items in the list remain unchanged.

Upvotes: 1

eumiro
eumiro

Reputation: 212845

robot_list = [Robot() for i in xrange(num_robots)]

creates num_robots instances of the Robot class and stores them into robot_list.

If you want to "name" them, i.e. the constructor gets a string as parameter, use this:

robot_list = [Robot('robot{}'.format(i)) for i in xrange(num_robots)]

Upvotes: 6

Paul Seeb
Paul Seeb

Reputation: 6146

You would need your robot class to take a string on initiallization (as its name). Note, when using the list of robots you would be acting on a robot object, not its name. However the robot would now have its name stored in the object.

class Robot():
    def __init__(roboName = ''):
        self.name = roboName

    # all other class methods after this

if __name__ == '__main__'
    robot_list = []
    for i in xrange (num_robots):
        robo_name = 'robot%s' % i
        robot_list.append(Robot(robo_name))

Upvotes: 0

Related Questions