Toán tử + dùng cả cộng số và nối chuỗi vì int và str đều nạp chồng +. Toán tử thực chất là method đặc biệt trong class. Định nghĩa method cho toán tử gọi là operator overloading. Ví dụ: dùng + với object tùy chỉnh → định nghĩa __add__.
Ví dụ: Cộng hai Circle
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def getRadius(self):
return self.__radius
def area(self):
return math.pi * self.__radius ** 2
def __add__(self, other):
if not isinstance(other, Circle):
return NotImplemented
return Circle(self.__radius + other.__radius)
c1 = Circle(3)
c2 = Circle(6)
c3 = c1 + c2 # Gọi c1.__add__(c2)
print(c3.getRadius()) # 9
Kết quả
3 6 9
Các method nạp chồng phổ biến
| Toán tử | Method |
|---|---|
+ | __add__ |
- | __sub__ |
* | __mul__ |
/ | __truediv__ |
== | __eq__ |
< | __lt__ |
[] | __getitem__, __setitem__ |
() | __call__ |
with | __enter__, __exit__ |
Xem docs.python.org/ref/specialnames.html để biết đầy đủ.