__setitem__ 在 Python 中为 Point(x,y) 类实现 [英] __setitem__ implementation in Python for Point(x,y) class

查看:52
本文介绍了__setitem__ 在 Python 中为 Point(x,y) 类实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中创建一个 Point 类.我已经实现了一些函数,比如 __ str__ 或 __ getitem__ ,而且效果很好.我面临的唯一问题是我的 __ setitem__ 实现不起作用,其他的都很好.

I'm trying to make a Point class in python. I already have some of the functions, like __ str__ , or __ getitem__ implemented, and it works great. The only problem I'm facing is that my implementation of the __ setitem__ does not work, the others are doing fine.

这是我的 Point 类,最后一个函数是我的 __ setitem__:

Here is my Point class, and the last function is my __ 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 应该像这样工作吗?)谢谢!

(Am I even right, should the setitem work like this?) Thanks!

推荐答案

self.data 和只有 self.data 保存坐标值.如果 self.xself.y 也存储这些值,则有机会 self.dataself.xself.y 不会持续更新.

Let self.data and only self.data hold the coordinate values. If self.x and self.y were to also store these values there is a chance self.data and self.x or self.y will not get updated consistently.

相反,使 xy self.data 中查找其值的noreferrer">属性.

Instead, make x and y properties that look up their values from self.data.

class Point(object):
    def __init__(self,x=0,y=0):
        self.data=[x, y]

    def __str__(self):
        return "point(%s,%s)"%(self.x,self.y)

    def __getitem__(self,item):
        return self.data[item]

    def __setitem__(self, idx, value):
        self.data[idx] = value

    @property
    def x(self):
        return self.data[0]

    @property
    def y(self):
        return self.data[1]

<小时>

声明

[self.x, self.y][x]=y

很有趣但有问题.让我们把它分开:

is interesting but problematic. Let pick it apart:

[self.x, self.y] 使 Python 构建一个新列表,其值为 self.xself.y.

[self.x, self.y] causes Python to build a new list, with values self.x and self.y.

somelist[x]=y 使 Python 将值 y 赋值给 somelistxth 索引.所以这个新列表 somelist 得到更新.但这对 self.dataself.xself.y 没有影响.这就是您的原始代码不起作用的原因.

somelist[x]=y causes Python to assign value y to the xth index of somelist. So this new list somelist gets updated. But this has no effect on self.data, self.x or self.y. That is why your original code was not working.

这篇关于__setitem__ 在 Python 中为 Point(x,y) 类实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆