0

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?

asked Apr 10, 2013 at 12:09

3 Answers 3

6
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)]
answered Apr 10, 2013 at 12:10
Sign up to request clarification or add additional context in comments.

1 Comment

I think I would give them a serial number instead. All of the robots which become sentient and try to take over the world have names ... Who ever heard of a robot 05XJ3DSA5 trying to take over the world?
1

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.

answered Apr 10, 2013 at 12:19

Comments

0

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))
answered Apr 10, 2013 at 12:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.