연산자 오버로딩: 비교

Python의 객체 지향 프로그래밍

Alex Yarosh

Content Quality Analyst @ DataCamp

객체 동등성

class Customer:
  def __init__(self, name, balance):
    self.name, self.balance = name, balance  


customer1 = Customer("Maryam Azar", 3000)
customer2 = Customer("Maryam Azar", 3000)

customer1 == customer2
False
Python의 객체 지향 프로그래밍

객체 동등성

class Customer:
  def __init__(self, name, balance, id):
    self.name, self.balance = name, balance
    self.id = id    

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
customer1 == customer2
False
Python의 객체 지향 프로그래밍

변수는 참조입니다

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
print(customer1)
<__main__.Customer at 0x1f8598e2e48>
print(customer2)
<__main__.Customer at 0x1f8598e2240>
Python의 객체 지향 프로그래밍

사용자 정의 비교

import numpy as np

# 동일한 데이터를 담은 두 다른 배열
array1 = np.array([1,2,3])
array2 = np.array([1,2,3])

array1 == array2
True
Python의 객체 지향 프로그래밍

__eq__() 오버로딩

class Customer:
  def __init__(self, id, name):
    self.id, self.name = id, name

# == 사용 시 호출됨 def __eq__(self, other):
# 진단용 출력 print("__eq__() is called") # 모든 속성이 같으면 True 반환 return (self.id == other.id) and \ (self.name == other.name)

 

 

  • __eq__()는 클래스의 두 객체를 ==로 비교할 때 호출됩니다
  • 인자: self, other — 비교 대상 객체
  • Boolean을 반환
Python의 객체 지향 프로그래밍

객체 비교

# 두 객체가 동일함

customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(123, "Maryam Azar")

customer1 == customer2
__eq__() is called
True
# 두 객체가 다름 - id가 다름

customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(456, "Maryam Azar")

customer1 == customer2
__eq__() is called
False
Python의 객체 지향 프로그래밍

기타 비교 연산자

연산자 메서드
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • 사전 키와 set에서 객체를 쓰려면 __hash__() 필요
Python의 객체 지향 프로그래밍

연습해 봅시다!

Python의 객체 지향 프로그래밍

Preparing Video For Download...