Usage to call a method of an instance before it is returned by __new__

__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

Usage to call a method of an instance before it is returned by __new__
How to create an instance of a particular class from dict using __new__ () in python
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
Is it possible to enter a venture before listing and make a lot of money with stock options?
What is Newton's method? ?? Approximate solution of equation to be solved by Newton's method
An easy way to measure the processing speed of a disk recognized by Linux
Don't take an instance of a Python exception class directly as an argument to the exception class!
Script to cancel an instance of Bluemix-IaaS (formerly SoftLayer)
How to deploy a Go application to an ECS instance
The copy method of pandas.DataFrame is deep copy by default
python (2) requires self because the method is an instance method
Created a class to check whether it is a constituent of TOPIX Core30, Large70, Mid400, Small
Create a 2D array by adding a row to the end of an empty array with numpy