[Python] 파이썬 객체 특수 메소드

hugingstar·2022년 4월 12일
0
post-thumbnail

1.__eq__ 함수

  • __eq__는 한 객체를 또 다른 객체와 크기 비교할 때 사용하는 함수이다. 한 객체가 담는 정보가 많은데 유일성을 자동적으로 판단할 수 있게 하려면 아래의 함수를 사용하면 좋다.

Example

  • Point라는 객체가 있고 Other 객체가 입력되었다고 했을 때, 두 객체가 동일한지 비교해보는 방법은 아래 예시와 같다.
  • Point라는 객체에는 pointName, object_type, device_id, object_id 같은 변수들이 선언되어 있다고 하면, 비교 대상이 되는 객체에도 pointName, object_type, device_id, object_id이 있을 수 있다.
  • 일차적으로 Point, Other이 모두 객체라는 게 확인이 되면 모든 변수들의 이름이 동일하면 동일한 객체이다 라는 True가 출력된다. 하나라도 다르다면? False가 출력된다.
class point():
 def __init__(self):
 
 ...
 
 def __eq__(self, other):
        if isinstance(other, Point):
            if (self.pointname == other.pointName and
                self.object_type == other.object_type and
                self.device_id == other.device_id and
                self.object_id == other.object_id):
                    return True
        else:
            return False

2. 다양한 객체함수 약어

  • A Less than B (A < B) : class.__lt__(입력변수)
  • A Less or equal B (A <= B) : class.__le__(입력변수)
  • A equal B (A == B) : class.__eq__(입력변수)
  • A not equal B (A != B) : class.__ne__(입력변수)
  • A greater than B (A > B) : class.__gt__(입력변수)
  • A greater or equal B (A>=) : class.__ge__(입력변수)

3. __hash__ 함수

  • Hashing : 많은 양의 데이터를 빠르게 저장, 삽입, 액세스하는 기법으로 해싱의 핵심은 데이터 저장, 검색할 때 시간을 줄이는 것.
  • 파이썬에서 딕셔너리도 해시의 한 예이다.

0개의 댓글