列举几个常用的魔术方法及其用途。

中等

答题要点

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

    # 字符串表示 (面向用户)
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

    # 开发者表示 (Debug用)
    def __repr__(self):
        return f"Vector(x={self.x}, y={self.y})"

    # 加法重载 (+)
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    # 相等判断 (==)
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # 调用 __add__

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题