본문 바로가기
컴퓨터 언어/Python

[ Python 3 ] Magic Methods 다루기 - 2. 비교 연산자 ( __eq__, __ne__, __lt__, __gt__, __le__, __ge__ )

by SuperMemi 2022. 8. 18.
반응형

[ Python 3 ] Magic Methods 다루기 - 2. 비교 연산자

 


[ 이전 글 ]

2022.08.17 - [컴퓨터 언어/Python] - [ Python 3 ] Magic Methods 다루기 - 1편 생성, 초기화 ( __new__, __init__, __del__ )

 

[ Python 3 ] Magic Methods 다루기 - 1편 생성, 초기화 ( __new__, __init__, __del__ )

[ Python 3 ] Magic Methods 다루기 - 1편 ( __new__, __init__, __del__ ) [ 매직 메소드(Magic Methods)? ] 다들 알고 계시겠지만 파이썬은 객체 지향 언어입니다. 모든 데이터들은 객체로 표현..

supermemi.tistory.com


[ 비교 매직 메소드란 무엇일까? ]

 

비교한다는 것은 어떤 것일까요?

 

예를 들어 생각해 봅시다.

숫자의 경우엔 1 보다 2가 큽니다. -1은 0보다 작습니다.

문자의 경우엔 문자열의 길이로 비교할 수 있습니다. 'apple'보다 'airplane'의 길이가 더 길죠. 또다른 기준으로는 알파벳의 오름차순으로 비교할 수도 있습니다.

 

이처럼 비교란 항상 어떤 기준이 있습니다.

 

마찬가지로 파이썬의 객체도 어떠한 기준 설정하여 비교할 수 있습니다.

 

하나씩 알아봅시다.


[ 비교 매직 메소드 종류 ]

 

  • __lt__(self, other) : x < y 를 판단하는 기준을 정의 (less than → lt)
  • __le__(self, other) : x ≤ y 를 판단하는 기준을 정의 (less than or equal to → le)
  • __gt__(self, other) : x > y 를 판단하는 기준을 정의 (greater than → gt)
  • __ge__(self, other) : x ≥ y 를 판단하는 기준을 정의 (greater than or equal to → ge)
  • __eq__(self, other) : x == y 를 판단하는 기준을 정의 (equal to → eq)
  • __ne__(self, other) : x != y 를 판단하는 기준을 정의 (not equal to → ne)

 

[ 예시 ]

문자열 객체의 길이를 비교하는 비교 매직 메소드를 설정해보자

 

[ 조건 ]

비교를 오직 문자열의 길이로 판단한다

문자열의 내용이 다르더라도 길이가 같으면 같다고 판단한다. 

 

[ 코드 ]

class Str_Comparison(str):
    def __new__(cls, string):
        return super(Str_Comparison, cls).__new__(cls, string)
    def __lt__(self, other):
        return len(self) < len(other)
    def __le__(self, other):
        return len(self) <= len(other)
    def __gt__(self, other):
        return len(self) > len(other)
    def __ge__(self, other):
        return len(self) >= len(other)
    def __eq__(self, other):
        return len(self) == len(other)
    def __ne__(self, other):
        return len(self) != len(other)
        
s1 = Str_Comparison('Jane')
s2 = Str_Comparison('James')
s3 = Str_Comparison('Peter')
s4 = Str_Comparison('Elizabeth')

print(s1 < s2) # True
print('Jane' < 'James') # False

print(s2 == s3) # True
print('James' == 'Peter') # False

print(s3 < s4) # True
print('Peter' < 'Elizabeth') # False

[ 결과 ]


[ 참고 ]

 

https://rszalski.github.io/magicmethods/


 

반응형