john
john

Reputation: 57

can i perform operator overloading of more than 2 objects in python?

class Point:

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

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

p1 = Point(2)
p2 = Point(2)
print("adding", p1 + p2)
output: 4

but if i do this,

class Point:

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

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

p1 = Point(2)  
p2 = Point(2)
p3 = Point(2)
print("adding", p1 + p2 + p3)

i get error:

print("adding", p1 + p2 + p3)
TypeError: unsupported operand type(s) for +: 'int' and 'Point'

can someone fix my program?

Upvotes: 0

Views: 1366

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55499

Your __add__ method is returning an int, but it really ought to return a Point instance: you're adding two Points together, so someone using that method would expect that the returned result is also a Point. But then the sum won't print nicely, unless you also supply __repr__ &/or __str__ methods; I've given simple examples of both below.

#!/usr/bin/env python

class Point:
    def __init__(self,x):
        self.x = x  

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

    def __repr__(self):
        return "Point({})".format(self.x)

    def __str__(self):
        return str(self.x)


p1 = Point(1)  
p2 = Point(2)
p3 = Point(4)

print("Points:", repr(p1), repr(p2), repr(p3))
print("adding", p1 + p2)
print("adding", p1 + p2 + p3)

output

Points: Point(1) Point(2) Point(4)
adding 3
adding 7

The __str__ method gets used when you convert an instance to a string, either explicitly, eg str(p1), or when print() does it for you. If a class doesn't have a __str__ method, its __repr__ method will be used instead, and if it doesn't have one of those, then the default one inherited from the parent object will be used.

"repr" is short for representation. The __repr__ method should return a string that looks like the call you use to create an instance of the class. This is handy in the interactive interpreter, since if you create any Python object in the interpreter without assigning it to a variable its repr gets printed. So you can copy & paste the repr of a class instance in the interpreter to create a new instance.

Upvotes: 3

user297171
user297171

Reputation:

Your __add__ method returns pure integer, not Point. Replace return x with return self or add a support for int argument in _add__

Upvotes: 1

Related Questions