[Python] __init__ vs __new__

넘실넘실·2025년 1월 29일

🔖 __init__

  • 새로 생성된 클래스 인스턴스를 초기화하는 역할
  • 첫 번째 인수를 self로 받고, 그 뒤에 추가 인수를 받음
  • __new__에 의해 인스턴스가 생성된 후, 호출자에게 반환되기 전에 호출됨
  • 베이스 클래스가 __init__() 메소드를 가지고 있다면 서브 클래스 __init__() 메소드는 명시적으로 호출해야 함
  • 인스턴스 메소드
  • 객체를 초기화하거나 객체의 속성을 설정할 때 사용한다

🔖 __new__

  • 클래스의 새 인스턴스를 생성하고 반환하는 역할
  • 첫 번째 인수를 cls로 받고, 그 뒤에 추가 인수를 받음
  • 정적 메소드
  • 객체 생성을 제어하거나 객체의 초기 상태를 설정할 때 사용한다

🖥️ Code Example

class Person:
    def __new__(cls, name, age):
        print("Creating a new Person object")
        instance = super().__new__(cls)
        return instance

    def __init__(self, name, age):
        print("Initializing the Person object")
        self.name = name
        self.age = age

person = Person("John Doe", 30)
print(f"Person's name: {person.name}, age: {person.age}")

# Creating a new Person object
# Initializing the Person object
# Person's name: John Doe, age: 30
  • __new__가 먼저 호출된 뒤 __init__이 호출됨
  • __init__ 함수로 객체를 생성하고 초기화

📑 reference

profile
어쩌다보니 데이터쟁이

0개의 댓글