跳到主要内容

写一个类,并让它尽可能多的支持操作符?

参考答案:

当然可以。下面是一个简单的Python类示例,该类支持多种操作符,包括算术操作符(如+-*/)、比较操作符(如==!=<><=>=)以及特殊方法(如__str____repr__)。

这个类名为Vector,代表一个二维向量,具有xy两个属性。

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

    # 算术操作符
    def __add__(self, other):
        if isinstance(other, Vector):
            return Vector(self.x + other.x, self.y + other.y)
        else:
            raise TypeError("Unsupported operand type for +")

    def __sub__(self, other):
        if isinstance(other, Vector):
            return Vector(self.x - other.x, self.y - other.y)
        else:
            raise TypeError("Unsupported operand type for -")

    def __mul__(self, other):
        if isinstance(other, Vector):
            raise TypeError("Vector multiplication is not supported")
        elif isinstance(other, (int, float)):
            return Vector(self.x * other, self.y * other)
        else:
            raise TypeError("Unsupported operand type for *")

    def __truediv__(self, other):
        if isinstance(other, (int, float)):
            return Vector(self.x / other, self.y / other)
        else:
            raise TypeError("Unsupported operand type for /")

    # 比较操作符
    def __eq__(self, other):
        if isinstance(other, Vector):
            return self.x == other.x and self.y == other.y
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __lt__(self, other):
        if isinstance(other, Vector):
            return self.x < other.x and self.y < other.y
        else:
            raise TypeError("Unsupported operand type for <")

    def __le__(self, other):
        if isinstance(other, Vector):
            return self.x <= other.x and self.y <= other.y
        else:
            raise TypeError("Unsupported operand type for <=")

    def __gt__(self, other):
        if isinstance(other, Vector):
            return self.x > other.x and self.y > other.y
        else:
            raise TypeError("Unsupported operand type for >")

    def __ge__(self, other):
        if isinstance(other, Vector):
            return self.x >= other.x and self.y >= other.y
        else:
            raise TypeError("Unsupported operand type for >=")

    # 特殊方法
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

    def __repr__(self):
        return self.__str__()

    # 为了方便,我们还可以定义`__neg__`方法来实现负号操作符
    def __neg__(self):
        return Vector(-self.x, -self.y)


# 使用示例
v1 = Vector(1, 2)
v2 = Vector(3, 4)

# 算术操作符
print(v1 + v2)  # Vector(4, 6)
print(v1 - v2)  # Vector(-2, -2)
print(v1 * 2)   # Vector(2, 4)
print(v1 / 2)   # Vector(0.5, 1.0)

# 比较操作符
print(v1 == v2)  # False
print(v1 != v2)  # True
print(v1 < v2)   # False
print(v1 <= v2)  # False
print(v1 > v2)   # False
print(v1 >= v2)  # False

# 特殊方法
print(str(v1))   # Vector(1, 2)
print(repr(v1))  # Vector(1, 2)
print(-v1)       # Vector(-1, -2)

这个Vector类支持多种操作符,包括加法、减法、乘法、除法、