Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with the __str__ method

Tags:

python

This is my script:

import math
class Vector:
    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y

    def ___str___(self):
        return "{0}, {1}".format(self.x, self.y)

    @classmethod
    def vectorPoints(cls, p1, p2):
        a = p2[0] - p1[0]
        b = p2[1] - p1[1]
        return Vector(a, b)

A = (1,5)
B = (2,7)
vectAB = Vector.vectorPoints(A, B)
print(vectAB)
vect = Vector(1, 0)
print(vect)

When I run this script I get:

<__main__.Vector object at 0x00FD5ED0>
<__main__.Vector object at 0x00FD5FF0>

Apparently the __str__ method isn't returning anything.

like image 847
marou Avatar asked Jul 07 '26 00:07

marou


2 Answers

The method name should be __str__ (2 underscores surrounding), not ___str___ (3 underscores surrounding).

like image 120
Jeff Mercado Avatar answered Jul 08 '26 13:07

Jeff Mercado


You are using three underscores (_) instead of the normal two.

like image 42
NobRuked Avatar answered Jul 08 '26 12:07

NobRuked