+ 오버로딩
비교 연산자만 오버로딩할 수 있는 것은 아니에요. Python의 클래스는 +, - 같은 산술 연산자에도 사용자 정의 동작을 구현할 수 있어요. 이 예제에서는 Storage 클래스에 대해 + 연산자를 오버로딩하는 연습을 해 보겠습니다.
이 연습은 강의의 일부입니다
Python 중급 객체 지향 프로그래밍
연습 안내
Storage클래스에 대해+연산자를 오버로딩하는 매직 메서드를 정의하세요.- 두 객체의
capacity를 합한 값과 같은capacity를 갖는 새Storage객체total_storage를 만드세요. onboard_storage와external_drive를 더해total_storage객체를 만들고,total_storage의capacity를 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
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.____)