-1
#
class Point:

def __init__(self, x, y):
    self.x = x
    self.y = y

def __add__(self, x, y):
    return self.x + self.y

def __sub__(self, x, y):
    return self.x - self.y

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2

print(p3)

OUTPUT: I get an an output which is looking for the parameter of y but i think i already pass y to it

Traceback (most recent call last):
  File "C:##################################", line 18, in <module>
    p3 = p1 + p2
TypeError: __add__() missing 1 required positional argument: 'y'
RY AN
  • 1
  • 3
    Does this answer your question? [How to properly overload the \_\_add\_\_ method?](https://stackoverflow.com/questions/36785417/how-to-properly-overload-the-add-method) – Maurice Meyer May 31 '20 at 09:06

2 Answers2

3

The expression p3 = p1 + p2 is in reality executed as:

p3 = p1.__add__(p2)

With your current function signature __add__(self, x, y), the Python interpreter will only receive self (p1), x (p2), but will be missing one argument (y), hence the error:

__add__() missing 1 required positional argument: 'y'

What you need instead, is an __add__ implementation (same goes for sub) which takes self and another point instance as arguments, and returns a new point:

class Point(object):
    def __add__(self, other: "Point") -> "Point":
        # returns a new point created by adding coordinates 
        # from self and the other point
Jon
  • 126
  • 3
-1

You need to indent the functions belonging to the class. Currently, Python thinks __add__ function has nothing to do with Point and has two arguments self and y. If it was indented, self would automatically be set to a reference to the instance.

The second issue is, in built-in magic methods, you only pass a reference to the other object explicitly and access the attributes of the calling object via self by the automatic referencing I mentioned.

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
curlycharcoal
  • 191
  • 1
  • 9