【问题标题】:Python append method adds object to the list [closed]Python append 方法将对象添加到列表中[关闭]
【发布时间】:2018-07-23 21:55:01
【问题描述】:

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

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)]

感谢您的帮助!


编辑:基于 cmets 的更正

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)

【问题讨论】:

  • 您忘记在def save_position(self, x, y): 中添加self。在您的实现中,x 将解析为当前实例。
  • 你忘记了self: def save_position(x, y): 你的参数是一个对象,而不是坐标。
  • 为什么在设置位置时要复制self.xself.y?为什么不直接self.x += a
  • 你还需要解压coord...robot.save_position(*coord)。或者您可以简单地将def save_position(x, y) 更改为def save_position(self, coord) 并摆脱或coord = x, y
  • @Jean-FrançoisFabre coord 是一个从 set_position 返回的元组

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


【解决方案1】:

我做了以下更改:

    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))

它带来了:

“位置”列表包含 (2, 3)

【讨论】:

  • 感谢@apet 的回答。
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多