시작하기무료로 시작하기

== 연산자 오버로딩

클래스 인스턴스를 비교할 때 Python의 내장 연산자는 매우 유용해요. 클래스를 만들 때는 매직 메서드를 사용해 이러한 연산자의 동작을 바꿀 수 있어요. 여기서는 두 Computer 인스턴스가 같은지 판단하도록 == 연산자를 오버로딩해 볼게요.

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

Python 중급 객체 지향 프로그래밍

강의 보기

연습 안내

  • == 연산자를 오버로딩하는 매직 메서드를 정의하세요.
  • 두 인스턴스가 같은지 판단하기 위해, 매직 메서드에서 selfotherdevice_id 속성을 비교하세요.
  • pre_upgrade_computerpost_upgrade_computer가 같은지 확인하고, 그 결과를 출력하세요.

실습형 인터랙티브 연습

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

class Computer:
  def __init__(self, device_id, storage):
    self.device_id = device_id
    self.storage = storage
  
  # Overload the == operator using a magic method
  def ____(self, other):
    # Return a boolean based on the value of device_id
    ____ self.____ == other.____

pre_upgrade_computer = Computer("Y391Hky6", 256)
post_upgrade_computer = Computer("Y391Hky6", 1024)

# Create two instances of Computer, compare using ==
print(____ == ____)
코드 편집 및 실행