我有以下代码。我想知道如何为labyrinth
我拥有机器人的对象创建尽可能多的属性。我有两个疑问,如何创建属性和如何调用函数。任何人 ?:)
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
第一个选项,使用 alist
来存储机器人:
class Labyrinth:
def __init__(self, obstacles, robots):
self.robots = robots
labyrinth = Labyrinth(obstacles, [robot1, robot2])
第二个选项,使用args
(robots
为了方便起见重命名为):
class Labyrinth:
def __init__(self, obstacles, *robots):
self.robots = robots
labyrinth = Labyrinth(obstacles, robot1, robot2)
然后,您可以访问每个机器人与名字labyrinth.robots[i].name
在那里i
是你想要的机器人的索引。
如果你真的想使用动态属性,你可以执行以下操作:
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"
但我建议你不要使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句