เรารู้ว่าเราสามารถใช้ตัวดำเนินการ + สำหรับบวกตัวเลข และในเวลาเดียวกันใช้สำหรับ Concatenate Strings ได้ สิ่งนี้เป็นไปได้เพราะตัวดำเนินการ + ถูก Overload โดยทั้ง Class int และ Class str ตัวดำเนินการพื้นฐานคือ Methods ที่ถูกกำหนดใน Class เหล่านั้น การกำหนด Methods สำหรับ Operators เรียกว่า Operator Overloading เช่น เพื่อใช้ + กับ Custom Objects เราต้องกำหนด Method ชื่อ __add__
ตัวอย่าง
โค้ดต่อไปนี้ทำให้เข้าใจง่ายว่า Operator Overloading ทำงานอย่างไร
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def setRadius(self, radius):
self.__radius = radius
def getRadius(self):
return self.__radius
def area(self):
return math.pi * self.__radius ** 2
def __add__(self, another_circle):
return Circle(self.__radius + another_circle.__radius)
c1 = Circle(3)
print(c1.getRadius())
c2 = Circle(6)
print(c2.getRadius())
c3 = c1 + c2 # นี้ทำงานเพราะเรา Overload + Operator โดยเพิ่ม Method __add__
print(c3.getRadius())
ผลลัพธ์
ได้ผลลัพธ์:
3
6
9
การปรับเปลี่ยนพฤติกรรมของ Operator ให้ทำงานกับ User-Defined Types เรียกว่า Operator Overloading สำหรับ Operator ทุกตัวใน Python มี Special Method ตรงกัน เช่น __add__ สำหรับรายละเอียดเพิ่มเติม ดูที่ docs.python.org/ref/specialnames.html