시작하기무료로 시작하기

클래스 동일성 확인하기

이전 연습 문제에서 비교에 사용되는 number 속성을 가진 BankAccount 클래스를 정의했어요. 그런데 number 속성이 있는 다른 클래스의 객체와 BankAccount 객체를 비교하면, 예기치 않은 결과가 나올 수 있습니다.

예를 들어, 다음 두 클래스를 살펴보세요.


class Phone:
  def __init__(self, number):
     self.number = number

  def __eq__(self, other):
    return self.number == \
          other.number

pn = Phone(873555333)

class BankAccount:
  def __init__(self, number):
     self.number = number

  def __eq__(self, other):
    return self.number == \
           other.number

acct = BankAccount(873555333)

acct == pn을 실행하면, 전화번호와 은행 계좌 번호를 비교하는 상황임에도 불구하고 True가 반환돼요.

비교가 타당한지 확인하려면 __eq__() 메서드에 전달된 객체의 클래스를 확인하는 것이 좋습니다.

이 연습은 강의의 일부입니다

Python의 객체 지향 프로그래밍

강의 보기

연습 안내

PhoneBankAccount 클래스가 모두 정의되어 있습니다. 먼저 "코드 실행" 버튼으로 코드를 그대로 실행해 보고, 출력 결과를 확인해 보세요.

  • BankAccount의 정의를 수정해, number 속성이 같고 두 객체의 type()이 동일할 때만 True를 반환하도록 하세요.

다시 코드를 실행하고 출력 결과를 확인해 보세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

class BankAccount:
    def __init__(self, number, balance=0):
        self.number, self.balance = number, balance
      
    def withdraw(self, amount):
        self.balance -= amount 

    # MODIFY to add a check for the type()
    def __eq__(self, other):
        return (self.number == other.number)

acct = BankAccount(873555333)
pn = Phone(873555333)
print(acct == pn)
코드 편집 및 실행