Skip to content Skip to sidebar Skip to footer

'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): tot

Solution 1:

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:

classVects:
    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)

Post a Comment for "'int' Object Has No Attribute 'x'"