Python มี Magic Methods เพื่อกำหนดพฤติกรรม Overloaded ของ Operators ตัวดำเนินการเปรียบเทียบ (<, <=, >, >=, == และ !=) สามารถ Overload ได้โดยการให้คำนิยามกับ Magic Methods __lt__, __le__, __gt__, __ge__, __eq__ และ __ne__ โปรแกรมต่อไปนี้ Overload < และ > เพื่อเปรียบเทียบออบเจ็กต์ของคลาส Distance
class Distance:
def __init__(self, x=5, y=5):
self.ft = x
self.inch = y
def __eq__(self, other):
if self.ft == other.ft and self.inch == other.inch:
return "both objects are equal"
else:
return "both objects are not equal"
def __lt__(self, other):
in1 = self.ft * 12 + self.inch
in2 = other.ft * 12 + other.inch
if in1 < in2:
return "first object smaller than other"
else:
return "first object not smaller than other"
def __gt__(self, other):
in1 = self.ft * 12 + self.inch
in2 = other.ft * 12 + other.inch
if in1 > in2:
return "first object greater than other"
else:
return "first object not greater than other"
d1 = Distance(5, 5)
d2 = Distance()
print(d1 > d2)
d3 = Distance()
d4 = Distance(6, 10)
print(d1 < d2)
d5 = Distance(3, 11)
d6 = Distance()
print(d5 < d6)
ผลลัพธ์แสดงการ Implement Magic Methods __lt__ และ __gt__
first object not greater than other
first object not smaller than other
first object smaller than other