[파이썬] __eq__ __lt__ 함수에 대해

프로그래밍/python2020. 12. 10. 11:53

Python에서 __eq__, __lt__ 등의 함수는 두 객체의 크기?를 비교할 때 사용되는 함수들입니다.

 

아래의 간단한 문장을 보면 이해가 쉽습니다.

 

x<y calls x.__lt__(y)

x<=y calls x.__le__(y)

x==y calls x.__eq__(y)

x!=y calls x.__ne__(y)

x>y calls x.__gt__(y)

x>=y calls x.__ge__(y).

 

lt는 less than 으로 < 를,

le는 less or equal로 <= 를,

eq는 equal로 ==를,

ne는 not equal로 !=를,

gt는 great than으로 >를,

ge는 great or equal로 >=를 의미합니다.

 

파이썬에서 새로 클래스/객체를 만들고 서로의 크기를 비교하려고 할 때 위의 함수들을 구현하면 됩니다. Java에서 보면 클래스를 만들고 Comparable 혹은 Comparator를 implements 해서 compareTo혹은 compare를 구현하는 것과 유사하네요.

 

아래와 같은 방식으로 구현할 수 있습니다.

class ListNode:
    def __eq__(self, other):
        return self.val == other.val

 

아래와 같이 lambda(a small anonymous function)로 표현할 수도 있어요. 람다의 문법은 아래와 같습니다. 콜론을 중심으로 함수의 인자와 표면이 나뉩니다.

lambda arguments : expression
ListNode.__eq__ = lambda self, other: self.val == other.val

 

 

 

참고

docs.python.org/3/reference/datamodel.html?highlight=__eq__#object.__lt__

 

3. Data model — Python 3.9.1 documentation

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define

docs.python.org

gmlwjd9405.github.io/2018/09/06/java-comparable-and-comparator.html

 

[Java] Comparable와 Comparator의 차이와 사용법 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

www.w3schools.com/python/python_lambda.asp

 

Python Lambda

Python Lambda A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. Syntax lambda arguments : expression The expression is executed and the result is returned: Example Add 10

www.w3schools.com

 

작성자

Posted by 드리머즈

댓글 영역