Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

__setitem__ implementation in Python for Point(x,y) class

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.

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

it should work like this:

p=point(2,3)
p[0]=1 #sets the x coordinate to 1
p[1]=10 #sets the y coordinate to 10

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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]

The statement

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

is interesting but problematic. Let pick it apart:

[self.x, self.y] causes Python to build a new list, with values self.x and self.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...