Search code examples
pythoninitialization

What can `__init__` do that `__new__` cannot?


In Python, __new__ is used to initialize immutable types and __init__ typically initializes mutable types. If __init__ were removed from the language, what could no longer be done (easily)?

For example,

class A:

    def __init__(self, *, x, **kwargs):
        super().__init__(**kwargs)
        self.x = x


class B(A):

    def __init__(self, y=2, **kwargs):
        super().__init__(**kwargs)
        self.y = y

Could be rewritten using __new__ like this:

class A_N:

    def __new__(cls, *, x, **kwargs):
        obj = super().__new__(cls, **kwargs)
        obj.x = x
        return obj


class B_N(A_N):

    def __new__(cls, y=2, **kwargs):
        obj = super().__new__(cls, **kwargs)
        obj.y = y
        return obj

Clarification for scope of question: This is not a question about how __init__ and __new__ are used or what is the difference between them. This is a question about what would happen if __init__ were removed from the language. Would anything break? Would anything become a lot harder or impossible to do?


Solution

  • Everything you can do in __init__ can also be done in __new__.

    Then, why use __init__?
    Because you don't have to store instance in variable (obj in your example code), and later bother returning it. You can focus on what you realy want to do – initializing mutable object.