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:
- First call
__new__(cls, arg1, arg2, key=value) to create the instance
- If
__new__ returns an instance of that class, then call __init__(self, arg1, arg2, key=value) to initialize the instance
- 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: ...
Class Instantiation Principles
When instantiating a class:
Python's call flow is:
__new__(cls, arg1, arg2, key=value)to create the instance__new__returns an instance of that class, then call__init__(self, arg1, arg2, key=value)to initialize the instance__new__and__init__When both
__new__and__init__methods exist, they will receive the same arguments.__init__Method ImpactIf the class explicitly declares an
__init__method, use that method's parameters directly to create the instance.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.__new__Method ImpactPriority 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 thenumpylibrary).