Member-only story
Magic Methods in Python
The so-called magic method, its official name is actually special method
, which is an advanced syntax of Python that allows you to customize functions in classes and bind them to special methods of classes. For example, if you define __str__ ()
function in class A, when calling str (A ()), it will automatically call __str__ ()
function and return the corresponding result.
__new__ and __init__
First, let’s talk about __new__
and __init__
. These two methods allow you to change the behavior when creating an object from a class, and these two are also relatively easy to mix up. If you don't know the mechanics of the two methods themselves, you just need to remember, __new__
is the process of creating an object from a class. And __init__
is the process of initializing this object after having this object.
class A:
def __new__(cls, *args, **kwargs):
print("__new__")
return super().__new__(cls, *args, **kwargs)
def __init__(self):
print("__init__")
if __name__ == '__main__':
a = A()
The output is:
__new__
__init__
We can see that both __new__
and __init__
are used. We can roughly imagine:
obj = __new__(A)
__init__(obj)