__new__
is a constructor that creates a new instance of that class, and __init__
is, as the name implies, an initializer for customizing a newly created instance. This official Python documentに説明されているとおり、__init__
は、__new__
が作成したインスタンスを、呼び出し元に返される前にself
として受け取ります。
In fact, it seems possible to use the instance method at that point, even inside __new__
, if the instance has already been created.
In the following sample code, immediately after creating an instance of Foo
using ʻobject .__ new in
Foo . new __, immediately call the ʻearly_call
instance method and set the instance variable self.arg
I have created it, but I am able to execute it properly.
python
class Foo:
def __new__(cls, arg):
instance = object.__new__(cls)
instance.early_call(arg)
return instance
def __init__(self, arg):
print(self.arg)
def early_call(self, arg):
self.arg = arg
foo = Foo("I'm foo.") # I'm foo.Is output.
In fact, the implementation of pandas MultiIndex uses this usage. I will.
Recommended Posts