Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python 비교 연산자를 오버로드하는 방법은 무엇입니까?


Python에는 연산자의 오버로드된 동작을 정의하는 마법의 메서드가 있습니다. 비교 연산자(<, <=,>,>=, ==및 !=)는 __lt__, __le__, __gt__, __ge__, __eq__ 및 __ne__ 매직 메서드에 정의를 제공하여 오버로드될 수 있습니다.

다음 프로그램 오버로드 ==및>=연산자를 사용하여 거리 클래스의 개체를 비교합니다.

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 __ge__(self, other):
                 in1=self.ft*12+self.inch
                 in2=other.ft*12+other.inch
                 if in1>=in2:
                    return "first object greater than or equal to other"
                  else:
                    return "first object smaller 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)

위 프로그램의 결과는 ==및>=비교 연산자의 과부하 사용을 보여줍니다.

both objects are equal
both objects are equal
first object smaller than other