시작하기무료로 시작하기

대체 생성자

Python에서는 @classmethod 데코레이터와 특별한 첫 번째 인수 cls를 사용해 클래스 메서드도 정의할 수 있어요. 클래스 메서드의 주요 목적은 __init__()과 동일한 코드를 쓰지 않으면서도, 해당 클래스의 인스턴스를 반환하는 메서드를 정의하는 데 있습니다.

예를 들어 시계열 패키지를 개발하면서 날짜를 다루기 위한 자체 클래스 BetterDate를 만들고자 한다고 해봅시다. 이 클래스의 속성은 year, month, day가 됩니다. 연도, 월, 일을 직접 값으로 받아 BetterDate 객체를 생성하는 생성자도 필요하지만, 2020-04-30처럼 문자열로부터 BetterDate 객체를 생성하는 기능도 원하신다고 합시다.

다음 함수들이 도움이 될 수 있어요:

  • .split("-") 메서드는 문자열을 "-" 기준으로 분할해 배열을 만듭니다. 예: "2020-04-30".split("-")["2020", "04", "30"]을 반환해요.
  • int()는 문자열을 숫자로 변환합니다. 예: int("2019")2019입니다.

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

Python의 객체 지향 프로그래밍

강의 보기

실습형 인터랙티브 연습

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

class BetterDate:    
    # Constructor
    def __init__(self, year, month, day):
      # Recall that Python allows multiple variable assignments in one line
      self.year, self.month, self.day = year, month, day
    
    # Define a class method from_str
    ____
    def from_str(____, datestr):
        # Split the string at "-" and convert each part to integer
        parts = datestr.split("-")
        year, month, day = int(parts[0]), ____, ____
        # Return the class instance
        ____ ____(____, ____, ____)
        
bd = BetterDate.from_str('2020-04-30')   
print(bd.year)
print(bd.month)
print(bd.day)
코드 편집 및 실행