我正在尝试在 python 中创建一个 Point 类。我已经实现了一些功能,例如 __ str__ 或 __ getitem__ ,并且效果很好。我面临的唯一问题是我对 __ setitem__ 的实现不起作用,其他的都很好。
这是我的 Point 类,最后一个函数是我的 __ setitem__()
:
class point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "point(%s,%s)" % (self.x, self.y)
def __getitem__(self, item):
return (self.x, self.y)[item]
def __setitem__(self, x, y):
[self.x, self.y][x] = y
它应该像这样工作:
p = point(2, 3)
p[0] = 1 # sets the x coordinate to 1
p[1] = 10 # sets the y coordinate to 10
我说得对吗,` setitem () 应该像这样工作吗?谢谢!
原文由 John Berry 发布,翻译遵循 CC BY-SA 4.0 许可协议
让
self.data
并且只有self.data
保存坐标值。 Ifself.x
andself.y
were to also store these values there is a chanceself.data
andself.x
orself.y
will无法持续更新。相反,使
x
和y
属性 从self.data
查找它们的值。该声明
很有趣但有问题。让我们把它分开:
[self.x, self.y]
导致 Python 构建一个 新列表,其值为self.x
和self.y
。somelist[x]=y
causes Python to assign valuey
to thex
th index ofsomelist
.所以这个新列表somelist
得到更新。但这对self.data
、self.x
或self.y
没有影响。这就是为什么您的原始代码不起作用的原因。