연산자 오버로딩: 객체 비교

Python 객체 지향 프로그래밍 입문

George Boorman

Curriculum Manager, DataCamp

객체 동등성

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

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

# Check for equality customer1 == customer2
False
Python 객체 지향 프로그래밍 입문

객체 동등성

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

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

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

변수는 참조입니다

customer_one = Customer("Maryam Azar", 3000, 123)
customer_two = Customer("Maryam Azar", 3000, 123)

print(customer_one)
<__main__.Customer at 0x1f8598e2e48>
print(customer_two)
<__main__.Customer at 0x1f8598e2240>
  • print() 출력은 변수에 할당된 메모리 위치를 나타냅니다
  • ==는 데이터가 아닌 참조를 비교합니다
Python 객체 지향 프로그래밍 입문

사용자 정의 비교

# Two different lists containing the same data
list_one = [1,2,3]
list_two = [1,2,3]

list_one == list_two
True
Python 객체 지향 프로그래밍 입문

__eq__() 메서드

  • ==로 클래스의 두 객체를 비교하면 __eq__()가 호출됩니다
  • 인수는 self, other 두 개이며, 비교 대상 객체입니다
  • 불리언을 반환합니다
Python 객체 지향 프로그래밍 입문

__eq__() 메서드

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

# Will be called when == is used def __eq__(self, other):
# Printout print("__eq__() is called") # Returns True if all attributes match return (self.acc_id == other.acc_id) and (self.name == other.name)
Python 객체 지향 프로그래밍 입문

객체 비교

# Two equal objects
customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(123, "Maryam Azar")

customer1 == customer2
__eq__() is called
True
# Two unequal objects - different ids
customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(456, "Maryam Azar")

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

타입 확인

  • 서로 다른 클래스의 두 객체가 같은 속성과 값을 가지면 어떻게 될까요?
    • 파이썬은 이를 같다고 평가합니다
class Customer:
    def __init__(self, acc_id, name):
        self.acc_id, self.name = idacc_id name

    def __eq__(self, other):
        # Returns True if the objects have the same attributes
        # and are of the same type
        return (self.acc_id == other.acc_id) and (self.name == other.name)\
            and (type(self) == type(other))
Python 객체 지향 프로그래밍 입문

기타 비교 연산자

Operator Method
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • 클래스 내에 정의하여 동작을 커스터마이즈합니다
Python 객체 지향 프로그래밍 입문

연습해 봅시다!

Python 객체 지향 프로그래밍 입문

Preparing Video For Download...