The difference between __init__ and __new__ in Python _python

Source: Internet
Author: User
Tags abs in python

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) C9/>if __name__ = = ' __main__ ':
  piglei = person (' Piglei ',)
  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 ',)
  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:

1.P = person (name, age)

2. First executes the __new__ method that uses the name and age parameters to execute the person class, and this __new__ method returns an instance of the person class (typically using the super (Persion, CLS). __new__ (CLS, ... ...) Such a way)

3. 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 themain difference between __init__ and __new__ is:

1.__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.
2.__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, we will only return this 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.