运算符重载
发布于 2021-05-22 Python Advance
Code:
123456789101112131415161718
class Vector: # 定义类基本属性 def __init__(self, a, b): self.a = a self.b = b # 定义返回字符串 def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) # 类自定义加法 def __add__(self, other): return Vector(self.a + other.a, self.b + other.b)v1 = Vector(2, 10)v2 = Vector(5, -2)print(v1 + v2)
Run:
1
Vector (7, 8)
上一篇: LeetCode-两数之和 下一篇: 类的继承