0

I am trying to override _add_ method. I am getting error : Point3 = Point1 + Point2 TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

What am I missing? Please help. This was my first Python class.

from math import sqrt                
            
class Point(object):

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

    def __str__(self):
        return "%i,%i,%i"%(self.x, self.y, self.z)
    
    def _add_(self, other):
        TotalX = self.x + other.x
        TotalY = self.y + other.y
        TotalZ = self.z + other.z
        return Point(TotalX, TotalY, TotalZ)

    def Distance(self, other):
        val =0
        val = ((self.x - other.x)**2+ (self.y - other.y)**2 + (self.z - other.z)**2)
        return val 

print ("Just defined method")    
Point1= Point(x=4, y=2, z=9)
Point2= Point(x=5, y=3, z=10)
Point3 = Point1 + Point2

            

Thanks, Shruti.

3
  • Your indenting is broken, please fix. Commented Mar 27, 2018 at 6:01
  • The indentation for the method Distance is not correct... Please Correct that by editing your question Commented Mar 27, 2018 at 6:04
  • Thanks Stephen and Harshit - That indentation issue was only while pasting it here. Alexander pointed out my mistake. Commented Mar 27, 2018 at 16:50

1 Answer 1

2

It's __add__, not _add_. All magic methods in Python, such as for addition, use two leading underscores and two trailing underscores. For a detailed reference on the Python data model, including all documented magic methods, please see here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Alexander. I wasted 1 hour in this error :(
@ShrutiSinghal If I've solved your question, please mark the question as answered. Glad to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.