Python append方法将对象添加到列表中

时间:2018-02-13 13:47:43

标签: python python-3.x list oop append

我有以下代码,这是一个非常简化的版本:

class Robot:

    def __init__(self, x, y):

        self.x = x
        self.y = y

    def set_position(self, a):

        x, y = self.x, self.y

        x = x + a
        y = y + a

        self.x = x
        self.y = y

        return self.x, self.y

    def save_position(x, y):

        coord = x, y
        positions = list(coord)

        print("The list 'positions' contains {0}".format(positions))



robot = Robot(1, 2)

coord = robot.set_position(1)
robot.save_position(coord)

结果是:

The list 'positions' contains [<__main__.Robot object at 0x02BE5490>, (2, 3)]

我不知道为什么对象会附加到列表中?我只需要附加坐标(2,3),得到以下结果:

The list 'positions' contains [(2, 3)]

感谢您的帮助!

编辑:基于评论的更正

class Robot:

    def __init__(self, x, y):

        self.x = x
        self.y = y

    def set_position(self, a):

        x, y = self.x, self.y

        self.x += a
        self.y += a

        return self.x, self.y

    def save_position(self, coord):

        x, y = coord
        positions = list()
        positions.append(coord)

        print("The list 'positions' contains {0}".format(positions))



robot = Robot(1, 2)

coord = robot.set_position(1)
robot.save_position(coord)

1 个答案:

答案 0 :(得分:0)

我做了以下更改:

    def set_position(self, a):
        coord=(self.x+a), (self.y+a)
        return (coord)
    def save_position(x, y):
        print("The list 'positions' contains {0}".format(coord))
它带来了:

列表&#39;位置&#39;包含(2,3)