Examples of the differences between __new__ and __init__ in Python

Source: Internet
Author: User
Tags abs in python


Examples of __new__ and __init__ differences

The most common use of __new__ and __init__ in Python is __init__,__init__, which is much like Php,c,java in other languages, but __new__ is similar to constructing methods and executes earlier than __init__. What's the difference between them? How do you use it?


What is the __init__ method?

Students who have written object-oriented code in Python may already be familiar with __init__ methods, and __init__ methods are often used when initializing a class instance. For example:

#-*-Coding:utf-8-*-

class Person (object):
"" "Silly Person" ""

def __init__ (self, Name, age):
Self.name = Name
Self.age = Age

def __str__ (self):
Return ' <person:%s (%s) > '% (Self.name, self.age)

if __name__ = = ' __main__ ':
Piglei = person (' Piglei ', 24)
Print Piglei
This is the most common use of __init__. But __init__ is not actually the first method that is invoked when instantiating a class. When an expression such as persion (name, age) is used to instantiate a class, the first method to be invoked is actually the __new__ method.

What is the __new__ method?
The __new__ method accepts the same parameters as __init__, but __init__ is called after the class instance is created, and the __new__ method is the method that creates the instance of the class.

#-*-Coding:utf-8-*-

class Person (object):
"" "Silly Person" ""

Def __new__ (CLS, name, age):
print ' __new__ called. '
Return super (person, CLS). __new__ (CLS, name, age)

def __init__ (self, Name, age):
print ' __init__ called. '
Self.name = Name
Self.age = Age

def __str__ (self):
Return ' <person:%s (%s) > '% (Self.name, self.age)

if __name__ = = ' __main__ ':
Piglei = person (' Piglei ', 24)
Print Piglei
Execution results:

piglei@macbook-pro:blog$ python new_and_init.py
__new__ called.
__init__ called.
<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 specific execution logic is this:

p = person (name, age)
First executes the __new__ method that uses the name and age parameters to execute the person class, and the __new__ method returns an instance of the person class (typically using the super (Persion, CLS). __new__ (CLS, ...) Such a way),
Then use this instance to invoke the __init__ method of the class, where the __new__ generated in the previous step is the self inside the __init__
So the main difference between __init__ and __new__ is:

__INIT__ is typically used to initialize a new instance to control the initialization process, such as adding some attributes and doing some extra work after the class instance has been created. It is an instance-level method.
__NEW__ is typically used to control the process of generating a new instance. It is a class-level method.
But what is the most common use of __new__, and when do we need __new__?

The role of __new__
According to the official Python documentation, the __new__ approach is primarily when you inherit immutable classes (such as int, str, tuple), which provides you with a way to customize the instantiation of the class. There is also the realization of custom metaclass.

First, let's take a look at the first feature that we can use int as an example:

If we needed an integer type that would always be positive, we might write this code by integrating int.

Class Positiveinteger (int):
def __init__ (self, value):
Super (Positiveinteger, self). __init__ (self, ABS (value))

i = Positiveinteger (-3)
Print I
But it turns out that the result is not what we thought it would be, and we got 3. This is because for an immutable object such as int, we only have to overload its __new__ method to play a custom role.

This is the modified code:

Class Positiveinteger (int):
Def __new__ (CLS, value):
Return Super (Positiveinteger, CLS). __new__ (CLS, ABS (value))

i = Positiveinteger (-3)
Print I
By overloading the __new__ method, we realize the required function.

Another function, about the custom metaclass. In fact, when I first contacted __new__, it was because of the need to customize Metaclass, but given the length of the reason, we next time to talk about the metaclass in Python and __new__ relationship.

Using __new__ to realize single case
In fact, when we understand the __new__ method, we can also use it to do some other interesting things, such as implementing the single case pattern (singleton) in the design pattern.

Because the process that the class produces after each instantiation is controlled by __new__, so we can implement the Singleton mode very simply by overloading the __new__ method.

Class Singleton (object):
def __new__ (CLS):
# The key is this, every time we instantiate it, we'll just return the same instance object.
If not hasattr (CLS, ' instance '):
Cls.instance = Super (Singleton, CLS). __new__ (CLS)
Return cls.instance

Obj1 = Singleton ()
Obj2 = Singleton ()

OBJ1.ATTR1 = ' value1 '
Print Obj1.attr1, OBJ2.ATTR1
Print Obj1 is Obj2
Output results:

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

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.