这是我的代码
class Shape(object):
def __init__(self, coords):
super(Shape, self).__init__()
self._coords = list(map(list, coords))
def move(self,distance):
self._coords = distance
def __getitem__(self,key):
return self._coords[key]
class Point(Shape):
def __init__(self,coords):
super(Point, self).__init__(coords)
if __name__ == '__main__':
p = Point((0, 0))
p.move((1, 1))
assert p[0, 0], p[0, 1] == (1, 1)
基本上,我想从父类Shape中创建一个子类Point。 形状的初始部分应保持不变,并尝试创建一个新点并通过“主要”项下的测试。
此代码现在变为错误TypeError:'int'对象不可迭代
作为Python的初学者,我对解决方案感到困惑。我可以将哪些参数传递给_coords以被接受?如何连接点和形状?
答案 0 :(得分:0)
class Shape(object):
def __init__(self, coords):
super(Shape, self).__init__()
self._coords = list(map(list, [coords])) # <--- to have it iterable enclose it in []
def move(self,distance):
self._coords = distance
def __getitem__(self,key):
return self._coords[key]
class Point(Shape):
def __init__(self,coords):
super(Point, self).__init__(coords)
if __name__ == '__main__':
p = Point((0, 0))
p.move((1, 1))
# the self._coords is a list, so fetch them by index like
assert p[0], p[1] == (1, 1)