0

I have the following code. I would like to know how I can create an as many attribute for the object labyrinth that I have robot. I have two doubts, how to create the attribute and how to call the function. Anyone ? :)

class Robot:

    """Class that represents a robot."""

    def __init__(self, name, x, y):
        self.name = name
        self.x = x
        self.y = y


class Labyrinth:

    """Class that represents a labyrinth."""

    def __init__(self, obstacles, *args):
        self.grid = {}
        for robot in args:  # First doubt
            self.robot.name = [robot.x, robot.y]  # First doubt


robot_1 = Robot(robot_1, 5, 6)
robot_2 = Robot(robot_2, 8, 9)
...
...
...
# unkown number of robots...

labyrinth = Labyrinth(obstacles, ......)  # Second doubt
5
  • You should create a list of robots instead of one attribute per robot. Commented Apr 30, 2018 at 16:08
  • Can you develop a little bit ? Do you mean to create a list that will contain all my robot and then loop on this list ? Thank you. (At first, it was my idea but I had difficulty to implement it. Commented Apr 30, 2018 at 16:10
  • Grille? Nom? You're making me hungry... Commented Apr 30, 2018 at 16:11
  • Sorry wrong translation from french to english. I corrected it. I will pay more attention next time. Commented Apr 30, 2018 at 16:15
  • @Tousalouest I've answer you in a post. Commented Apr 30, 2018 at 16:23

1 Answer 1

1

First option, using a list to store the robots:

 class Labyrinth:
    def __init__(self, obstacles, robots):
        self.robots = robots

labyrinth = Labyrinth(obstacles, [robot1, robot2]) 

Second option, using args (renamed to robots for convenience):

 class Labyrinth:
    def __init__(self, obstacles, *robots):
        self.robots = robots

labyrinth = Labyrinth(obstacles, robot1, robot2) 

Then, you can access each robot's name with labyrinth.robots[i].name where i is the index of the robot you want.

If you really want to use dynamic attributes, you can do the following:

class A:    
    def __init__(self, *args):
        for idx, arg in enumerate(args):
            setattr(self, 'arg_' + str(idx), arg)

a = A(1,2,3,4)
print(a.arg_0, a.arg_1, a.arg_2, a.arg_3) # print "1 2 3 4"

but I suggest you to not use that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.