Michael Michael - 28 days ago 6
Python Question

'int' object has no attribute 'x'

I'm trying to make a program to add vectors using

__add __
:

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

def __add__(self, vect):
total_x = self.x + vect.x
total_y = self.y + vect.y
return vects(total_x, total_y)

plusv1 = vects.__add__(2,5)
plusv2 = vects.__add__(1,7)
totalplus = plusv1 + plusv2


The error produced is as follows:

line 12, in <module> plusv1 = vects.__add__(2,5)
line 7, in __add__ total_x = self.x + vect.x
AttributeError: 'int' object has no attribute 'x'

Answer

You don't use __add__ like that! :-) __add__ will get implicitly invoked when + is used on an instance of the Vects class.

So, what you should first do is initialize two vector instances:

v1 = Vects(2, 5)
v2 = Vects(1, 7)

and then add them:

totalplus = v1 + v2

If you add a nice __str__ to get a nice representation of your new vector:

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

    def __add__(self, vect):
        total_x = self.x + vect.x
        total_y = self.y + vect.y
        return Vects(total_x, total_y)

    def __str__(self):
        return "Vector({}, {})".format(self.x, self.y)

You can get a view of totalplus by printing it:

print(totalplus)
Vector(3, 12)