Python Forum
Please help! Problem with my Point object - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Please help! Problem with my Point object (/thread-16564.html)



Please help! Problem with my Point object - itrema - Mar-05-2019

Hello everyone! I am having a problem with my code and after minutes of search, I landed here. I need your help.

Here is the problem: We want to create a Point object capable of handling the most basic vector operations; we want our Point object to handle addition and subtraction. For two points (x1,y1)+(x2,y2)=(x1+x2,y1+y2) and similarly for subtraction. Implement a method within Point that allows two Point objects to be added together using the + operator, and likewise for subtraction.

Here is my code:
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Point({0}, {1})".format(self.x, self.y)
    def __add__(self, other):
        a = self.x + other.x
        b = self.y + other.y
        return "Point({a}, {b})"
    def __sub__(a, b):
        c = self.x - other.x
        d = self.y - other.y
        return "Point({c}, {d})"
And I've got type erreor.
Can anyone help me?
By the way if you have an idea for multiplication, I'll be....


RE: Please help! Problem with my Point object - DeaD_EyE - Mar-05-2019

class Point(object):
    __slots__ = ['x', 'y']
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Point({0}, {1})".format(self.x, self.y)
    def __add__(self, other):
        x, y = self.x + other.x, self.y + other.y
        return self.__class__(x, y)
    def __sub__(self, other):
        x, y = self.x - other.x, self.y - other.y
        return self.__class__(x, y)

  1. added __slots__ to save memory of the crated object from class
  2. method signature of sub was wrong
  3. A Point should be immutable. Doing an operation with two points, should return a new point.

    Instead of self.__class__, you can use also direct the name Point.
    The first one is good for inheritance.

For training, you could add other methods. For example a conversion to polar coordinates: https://en.wikipedia.org/wiki/Polar_coordinate_system#Converting_between_polar_and_Cartesian_coordinates

You can use a new class for this different representation or you do it inside of the Point class, maybe as a property.


RE: Please help! Problem with my Point object - itrema - Mar-05-2019

Thank you very much for your help. It worked