Why do all objects get populated with the same coordinates?

pet*_*ojs 1 python

I'm creating a program for a robot to map out a labyrinth. I'm doing this in Python and the problem is when I'm trying to create a 3D array with my objects by looping through it, somehow every object gets populated with [9, 9, 2].

class Field:
    coordinates = {}

    def __init__(self, x_arg, y_arg, z_arg = None):
        self.coordinates['x'] = x_arg
        self.coordinates['y'] = y_arg
        if z_arg is not None:
            self.coordinates['z'] = z_arg
        else:
            self.coordinates['z'] = 0

    def update_location(self, x_arg, y_arg, z_arg = None):
        del self.coordinates['x']
        del self.coordinates['y']

        self.coordinates['x'] = x_arg
        self.coordinates['y'] = y_arg

        if z_arg is not None: 
            del self.coordinates['z']
            self.coordinates['z'] = z_arg

    def __repr__(self):
        return "[" + str(self.coordinates['x']) + ", " + str(self.coordinates['y']) + ", " + str(self.coordinates['z']) + "]"

    def __str__(self):
        return "[" + str(self.coordinates['x']) + ", " + str(self.coordinates['y']) + ", " + str(self.coordinates['z']) + "]"


map = [[[Field(current_x, current_y, current_z) for current_z in xrange(3)] for current_y in xrange(10)] for current_x in xrange(10)]
Run Code Online (Sandbox Code Playgroud)

Car*_*cho 5

您已经coordinates在类级别进行了定义,以便在所有Field实例之间共享属性。要解决此问题,请尝试coordinates__init__方法中进行定义:

class Field:

    def __init__(self, x_arg, y_arg, z_arg = None):
        self.coordinates = {}
        self.coordinates['x'] = x_arg
        self.coordinates['y'] = y_arg
        ...
Run Code Online (Sandbox Code Playgroud)