시작하기무료로 시작하기

+ 오버로딩

비교 연산자만 오버로딩할 수 있는 것은 아니에요. Python의 클래스는 +, - 같은 산술 연산자에도 사용자 정의 동작을 구현할 수 있어요. 이 예제에서는 Storage 클래스에 대해 + 연산자를 오버로딩하는 연습을 해 보겠습니다.

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

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

강의 보기

연습 안내

  • Storage 클래스에 대해 + 연산자를 오버로딩하는 매직 메서드를 정의하세요.
  • 두 객체의 capacity를 합한 값과 같은 capacity를 갖는 새 Storage 객체 total_storage를 만드세요.
  • onboard_storageexternal_drive를 더해 total_storage 객체를 만들고, total_storagecapacity를 출력하세요.

실습형 인터랙티브 연습

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

class Storage:
  def __init__(self, capacity):
    self.capacity = capacity
  
  def ____(____, ____):  # Overload the + operator
    # Create a Storage object with the sum of capacity
    return ____(self.____ + other.____)

onboard_storage = Storage(128)
external_drive = Storage(64)

# Add the two Storage objects, show the total capacity
total_storage = ____ + ____
print(total_storage.____)
  
코드 편집 및 실행