简体   繁体   中英

Problem with the __str__ method

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.

方法名称应该是__str__ (周围有2个下划线),而不是___str___ (周围有3个下划线)。

您使用三个下划线( _ )而不是正常的两个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM