Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để triển khai các toán tử tùy chỉnh (quá tải) trong Python __lt__ __gt__?


Python có các phương thức ma thuật để xác định hành vi quá tải của các toán tử. Các toán tử so sánh (<, <=,>,> =, ==và! =) Có thể được nạp chồng bằng cách cung cấp định nghĩa cho các phương thức ma thuật __lt__, __le__, __gt__, __ge__, __eq__ và __ne__. Chương trình sau sẽ nạp chồng các toán tử để so sánh các đối tượng của lớp khoảng cách.

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)

Kết quả hiển thị việc triển khai các phương pháp phép thuật __lt__ và _gt__

first object not greater than other
first object not smaller than other
first object smaller than other