The difference between __init__ and __new__ in Python

Source: Internet
Author: User
Tags abs

First, what is the __init__ method? (the lines before and after Init are double-underlined)

Students who have written object-oriented code in Python may be familiar with the __init__ method, and the __init__ method is often used to initialize a class instance. For example:

1 #-*-Coding:utf-8-*-2  3 class Person (object): 4 "" "Silly Person" ""     5  6     def __init__ (self, name, age) : 7         self.name = name 8         self.age = age 9     def __str__ (self):         return ' <person:%s (%s) > '% (self.na Me, self.age) if __name__ = = ' __main__ ': +     Piglei = person (' Piglei ', ')     print Piglei

This is the most common usage of __init__. But __init__ is not actually the first method to be called when instantiating a class. When an expression such as persion (name, age) is used to instantiate a class, the first method to be called is actually the __new__ method.

Second, what is the __new__ method?

The __new__ method accepts parameters that are the same as __init__, but __init__ is called after the class instance is created, and the __new__ method is the way to create the class instance.

1 #-*-Coding:utf-8-*-2  3 class Person (object): 4 "" "Silly Person" ""     5  6     def __new__ (CLS, name, age): 7         print ' __new__ called. ' 8         return Super (person, CLS). __new__ (CLS, name, age) 9     def __init__ (self, Name, age):         print ' __init__ cal LED. '         self.name = name13         self.age = Age14     def __str__ (self):         return ' <person:%s (%s) > '% ( Self.name, self.age) if __name__ = = ' __main__ ':     piglei = person (' Piglei ', ')     print Piglei

Execution Result:

1 [email protected]:blog$ python new_and_init.py2 __new__ Called.3 __init__ Called.4 <person:piglei ($) >

By running this code, we can see that the invocation of the __new__ method occurred before __init__. In fact, when you instantiate a class, the concrete execution logic is this:

1.P = person (name, age)
2. First execute the __new__ method that uses the name and age parameters to execute the person class, which returns an instance of the person class (typically using super (Persion, CLS). __new__ (CLS, ...) Such a way),
3. Then use this example to invoke the __init__ method of the class, the __new__ generated in the previous step is the self within the __init__

So the main difference between __init__ and __new__ is that:
1.__INIT__ is typically used to initialize a new instance, controlling the initialization process, such as adding properties and doing additional operations that occur after the class instance is created. It is an instance-level method.
2.__NEW__ is typically used to control the process of generating a new instance. It is a class-level method.
But when we say so much, what is the most common usage of __new__, and when do we need __new__?

Third, the role of __new__

According to the official Python document, the __new__ method is primarily when you inherit some immutable classes (such as int, str, tuple), providing you with a way to customize the instantiation process for the class. There is also the implementation of custom Metaclass.
First, let's take a look at the first feature, we can use int as an example:
If we need an integer type that is always positive, we might write this code by integrating int.

1 class positiveinteger (int): 2 def __init__ (self, Value): 3 Super (Positiveinteger, self). __init__ (Self, ABS (val UE)) 4 5 i = Positiveinteger ( -3) 6 Print I

But after the run we will find that the result is not what we thought, we still got-3. This is because for an immutable object such as int, we only have to reload its __new__ method to be able to customize the function.
This is the modified code:

1 class positiveinteger (int): 2 def __new__ (CLS, value): 3 Return Super (Positiveinteger, CLS). __new__ (CLS, ABS (v Alue)) 4 5 i = Positiveinteger ( -3) 6 Print I

By overloading the __new__ method, we implemented the required functionality.
In addition a function, about custom metaclass. In fact, when I first approached __new__, it was because of the need to customize the Metaclass, but for the space reasons, we will talk about Python next time metaclass and __new__ relationship.

Iv. using __new__ to achieve a single case

In fact, when we understand the __new__ method, we can also use it to do some other interesting things, such as implementing a singleton pattern (singleton) in design patterns.
Because the process of every instantiation of a class is controlled by __new__, we can easily implement a singleton mode by overloading the __new__ method.

1 class Singleton (object): 2 def __new__ (CLS): 3 # The key is this, every time we instantiate, we only return this same instance object 4 if not Hasa TTR (CLS, ' instance '): 5 cls.instance = Super (Singleton, CLS). __new__ (CLS) 6 return cls.instance 7  8 obj1 = Singleton () 9 obj2 = Singleton () Ten obj1.attr1 = ' value1 ' Print obj1.attr1, obj2.attr113 print obj1 is Obj2

Output Result:

Value1 value1
True

You can see that obj1 and Obj2 are the same instance.

The difference between __init__ and __new__ in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.