Skip to content

Python Class initialization method parameter selection #48

Description

@toaction

Class Instantiation Principles

When instantiating a class:

obj = MyClass(arg1, arg2, key=value)

# Equivalent to
temp = MyClass.__new__(MyClass, arg1, arg2, key=value)
if isinstance(temp, MyClass):
    temp.__init__(arg1, arg2, key=value)
obj = temp

Python's call flow is:

  1. First call __new__(cls, arg1, arg2, key=value) to create the instance
  2. If __new__ returns an instance of that class, then call __init__(self, arg1, arg2, key=value) to initialize the instance
  3. Arguments are passed to both __new__ and __init__

When both __new__ and __init__ methods exist, they will receive the same arguments.

__init__ Method Impact

If the class explicitly declares an __init__ method, use that method's parameters directly to create the instance.

class Dog(Animal):
    def __init__(self, name):
        self.name = name

If no __init__ method is explicitly declared, the inheritance relationship and MRO (Method Resolution Order) need to be considered. When there are multiple parent classes, Python will call the first parent class with an __init__ in the MRO.

class A:
    def __init__(self):
        print("A __init__")
class B:
    def __init__(self):
        print("B __init__")

class C(A, B):
    pass


c = C()   # Output "A __init__"

__new__ Method Impact

Priority is given to the parameters declared in the __init__ method. If the class has no parent class and no explicitly declared __init__ method, consider using the __new__ method parameters to create the instance (commonly seen in C-implemented classes under the numpy library).

class ndarray:
    def __new__(
        cls: type[_ArraySelf],
        shape: _ShapeLike,
        dtype: DTypeLike = ...,
        buffer: None | _SupportsBuffer = ...,
        offset: SupportsIndex = ...,
        strides: None | _ShapeLike = ...,
        order: _OrderKACF = ...,
    ) -> _ArraySelf: ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions