简述写Python一个类,并让它尽可能多的支持操作符? ?
参考答案:
在Python中,我们可以通过定义类的特殊方法(也称为魔法方法或双下划线方法)来支持各种操作符。以下是一个示例,这个类Vector
表示二维向量,并尽可能多地支持操作符:
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):
return self.x * other.x + self.y * other.y
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 __neg__(self):
return Vector(-self.x, -self.y)
# 支持比较操作
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, self.y) < (other.x, other.y)
else:
raise TypeError("Unsupported operand type for <")
def __le__(self, other):
if isinstance(other, Vector):
return (self.x, self.y) <= (other.x, other.y)
else:
raise TypeError("Unsupported operand type for <=")
def __gt__(self, other):
if isinstance(other, Vector):
return (self.x, self.y) > (other.x, other.y)
else:
raise TypeError("Unsupported operand type for >")
def __ge__(self, other):
if isinstance(other, Vector):
return (self.x, self.y) >= (other.x, 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__()
在这个类中,我们定义了加法、减法、乘法、除法、取反、比较操作等方法,使得我们可以对Vector
对象执行这些操作。注意,这些方法应该尽可能地检查操作数类型,并在类型不匹配时抛出TypeError
。
然后,我们可以像下面这样使用这个类:
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
print(v1 - v2) # Vector(-2, -2)
print(v1 * v2) # 11
print(v1 * 2) # Vector(2, 4)
print(-v1) # Vector(-1, -2)
print(v1 == v2) # False
print(v1 != v2) # True
print(v1 < v2) # True
print(v1 <= v2) # True
print(v1 > v2) # False
print(v1 >= v2) # False
这个类尽可能地支持了Python中的操作符,使得我们可以更方便地使用Vector
对象进行各种操作。