Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__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!

like image 246
John Berry Avatar asked Apr 02 '13 21:04

John Berry


People also ask

What is __ Setitem __ in Python?

Python's magic method __setitem__(self, key, value) implements the assignment operation to self[key] . So, if you call self[key] = value , Python will call self. __setitem__(key, value) . We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”).

How does Setitem work in Python?

__setitem__ is a method used for assigning a value to an item. It is implicitly invoked when we set a value to an item of a list, dictionary, etc. __getitem__ is a method used for getting the value of an item. It is implicitly invoked when we access the items of a list, dictionary, etc.

What is __ class __ in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .

What is __ add __ in Python?

Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator “+” in Python.


1 Answers

This is pretty old post, but the solution for your problem is very simple:

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.__dict__[item]

    def __setitem__(self,item,value):
        self.__dict__[item] = value

Each class has his own dictionary with all properties and methods created inside the class. So with this you can call:

In [26]: p=point(1,1)
In [27]: print p
point(1,1)
In [28]: p['x']=2
In [29]: print p
point(2,1)
In [30]: p['y']=5
In [31]: print p
point(2,5)

It is more readable then your "index" like reference.

like image 80
Gregory Avatar answered Nov 15 '22 14:11

Gregory