python - 'int' object has no attribute 'x' -


i'm trying make program 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 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'  

you don't use __add__ that! :-) __add__ implicitly invoked when + used on instance of vects class.

so, should first initialize 2 vector instances:

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

and add them:

totalplus = v1 + v2 

if add nice __str__ nice representation of 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 view of totalplus printing it:

print(totalplus) vector(3, 12) 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -