Where is the python instantiation process written?

When initializing an instance with python, it is often described in a special method called __init __ (), but the instance is not created here. While confirming that fact, let's find out where the process of creating an instance is written.

** Execution environment **

Name Version
python 3.4.3
ipython 3.1.0

new is executed before init

class Foo():
    def __init__(self):
        print('init')
        print('self = %s' % self)

Foo()
# => 
# init
# self = <__main__.Foo object at 0x10dacb9b0> 

Writing Class () will call the special method __init__ of that class. This is an instance method. The reason is that it takes an argument of self, that is, an instance. The variable name self is not grammatically fixed, so you can use another name, but it seems that it is customarily used as self.

So where is this instance created? First, let's suppress new that is executed before __init __ ().

[Official Document](http://docs.python.jp/3.4/reference/datamodel.html?highlight=%E7%89%B9%E6%AE%8A%E3%83%A1%E3%82%BD% E3% 83% 83% E3% 83% 89 # specialnames) states that __new__ () will be called to create a new instance. And this __new__ () is automatically defined at the time of class creation even if it is not specified.

class Foo():
    def __init__(self):
        pass

foo = Foo()
`__new__' in dir(foo)
# =>  True

You can also see in the official documentation that this __new __ () is executed before the __init __ ().

If new () returns an instance of cls, then the instance init () is called like init (self [, ...]). At this time, self is the newly created instance, and the remaining arguments are the same as those passed to new (). 3. Data model — Python 3.4.3 Documentation </ cite>

This can be confirmed in the source code below.

class Foo():
    def __new__(cls, var1):
        print('new')
        print('var1 = %s' % var1)
        return super().__new__(cls)

    def __init__(self, var1):
        print('init')
        print('self = %s' % self)
        print('var1 = %s' % var1)

Foo('my_value')
# => 
# new
# var1 = my_value
# init
# self = <test.Foo object at 0x103bd0208> 
# var1 = my_value * Up to here is print()It is the output in.
#<test.Foo at 0x103bd0208> 

super () calls the parent class. This time, the instance creation is left to the parent class. Since it overrides __new__ (), I used super (). __ new__ (cls) to write the process of explicitly instantiating myself.

Where are the inherited methods?

Even if you do not override __new__ (), if you leave the instance creation to the parent class __new__ (), the real instance creation process is written in the __new__ () of all parent classes object. It will be done. Alternatively, the instantiation process may be written in __new__ () of each class.

I still didn't know where the instantiation process was written. However, I found that ** Class () was calling __new__ **.

To confirm that the processing of this __new__ () is written, you can find it by executing it without parentheses () in the method name.

class Super():
    @classmethod
    def hello(cls):
        print('super hello')

    @classmethod
    def say(cls):
        print('super say')

class Sub(Super):
    @classmethod
    def hello(cls):
        print('super hello')

#Check the method you defined and the class where it is defined
Super.hello
# => <bound method type.hello of <class 'test.Super'> > 
Sub.hello
# => <bound method type.hello of <class 'test.Sub'> > 

#If not overridden
Sub.say
# => <bound method type.say of <class 'test.Sub'> > 

Super.__new__
# => <function object.__new__> 
Super.__init__
# => <slot wrapper '__init__' of 'object' objects> 
Super.__le__
# => <slot wrapper '__le__' of 'object' objects> 

Not only __new__, but other special methods themselves are defined by object. It turns out that all objects are left to object to instantiate unless overridden.

Recommended Posts

Where is the python instantiation process written?
Automatically get the port where Arduino is stuck in Python
[Python] What is @? (About the decorator)
[python] What is the sorted key?
What is the python underscore (_) for?
[Python] The value written in Openpyxl is displayed in exponential notation (E).
[Unix] What is the zombie process / orphan process?
What is "mahjong" in the Python library? ??
[python] [meta] Is the type of python a type?
Set the process name of the Python program
Python is easy
The answer of "1/2" is different between python2 and 3
[Xonsh] The Python shell is sharp and god
What is wheezy in the Docker Python image?
Wagtail is the best CMS for Python! (Perhaps)
About the difference between "==" and "is" in python
Send Gmail at the end of the process [Python]
This is the only basic review of Python ~ 1 ~
This is the only basic review of Python ~ 2 ~
What is python
I'm new to Python. Could you please tell me where the error is?
Python is instance
This is the only basic review of Python ~ 3 ~
Get the region where AWS Lambda is running
Run the Blue Prism process using Python (SOAP)
What is Python
Around the place where the value of Errbot is stored
The process of installing Atom and getting Python running
Python3 datetime is faster just by specifying the timezone
Is the Python 3 Engineer Certification Basic Exam Really Easy?
What is the domain attribute written in Plotly's Layout?
Find the part that is 575 from Wikipedia in Python
Electron is the best solution for Python multi-platform development
Why is the first argument of [Python] Class self?
Using the LibreOffice app in Python (1) Where are the macros?
[Python] Make sure the received function is a user-defined function
python (2) requires self because the method is an instance method
python int is infinite
Find the maximum Python
[Python] What is Pipeline ...
the zen of Python
Daemonize a Python process
[Python] Split the date
[Python] What is virtualenv
Which is the most popular python visualization tool after all?
I want to initialize if the value is empty (python)
Test.py is not reflected on the web server in Python3.
Output "Draw ferns programmatically" to the drawing process in Python
'De' =='De' is False! Actually, the second "de" was two letters. [Python]
[Python] Which is executed first, the class variable or __init__?
Debug by attaching to the Python process of the SSH destination
[Python] Is the zero but non-empty object Truthy or Fallsy?
The process of making Python code object-oriented and improving it
What is the default TLS version of the python requests module?
Get the class name where the method is defined in the decorator
Initial setting of Mac ~ Python (pyenv) installation is the fastest
After deleting the Java process log, the log is no longer output