The differences between _ init _ and _ new _ in Python are described in detail, __init ___ new _

Source: Internet
Author: User

The differences between _ init _ and _ new _ in Python are described in detail, __init ___ new _

What is the _ init _ method?

If you have written object-oriented code using Python, you may be familiar with the _ init _ method, and the _ init _ method is usually used to initialize 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 usage of _ init. But _ init _ is not the first method called when instantiating a class. When an expression like Persion (name, age) is used to instantiate a class, the first method called is actually the _ new _ method.

_ New _ What is the method?

Although the parameters accepted by the _ new _ method are the same as those accepted by the _ init _ method, the _ init _ method is called after the class instance is created, the _ new _ method is the method used to create this class instance.

# -*- 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 result:

piglei@macbook-pro:blog$ python new_and_init.py__new__ called.__init__ called.<Person: piglei(24)>

By running this code, we can see that the _ new _ method is called before _ init. In fact, when you instantiate a class, the specific execution logic is as follows:

1. p = Person (name, age)

2. first, run the _ new _ method of the Person class using the name and age parameters, this _ new _ method returns an instance of the Person class (usually super (Persion, cls ). _ new _ (cls ,......) in this way)

3. Use this instance to call the _ init _ method of the class. In the previous step, the _ new _ generated instance is the self in _ init _.

So,The main difference between _ init _ and _ new _ is:

1. _ init _ is usually used to initialize a new instance and control the initialization process. For example, you can add some attributes and perform some additional operations after the class instance is created. It is an instance-level method.
2. _ new _ is usually used to control the process of generating a new instance. It is a Class-level method.

However, when do we need _ new __?

_ New _

According to the official Python documentation, the __new _ method is mainly used when you inherit some immutable classes (such as int, str, tuple ), it provides you with a way to customize the instantiation process of these classes. The custom metaclass is also implemented.

First, let's look at the first function. We can use int as an example:

If we need an integer that is always positive, we may 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 after running it, we will find that the result is not what we thought at all, and we have got-3. This is because for an immutable object such as int, we only need to overload its _ new _ method to play a custom role.

Here 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 reloading the _ new _ method, we have implemented the required functions.

Another function is about custom metaclass. In fact, when I first came into contact with _ new _, it was because I needed to customize metaclass. However, for space reasons, we will next talk about the relationship between metaclass and _ new _ in python.

Use _ new _ to implement Singleton

In fact, when we understand the _ new _ method, we can also use it to do other interesting things, such as implementing singleton in design patterns ).

Because the process generated after each class instantiation is controlled by _ new _, we can easily implement the singleton mode by reloading the _ new _ method.

Class Singleton (object): def _ new _ (cls): # The key lies in this. During each instantiation, we will only return the same instance object if not hasattr (cls, 'instance'): cls. instance = super (Singleton, cls ). _ new _ (cls) return cls. instanceobj1 = Singleton () obj2 = Singleton () obj1.attr1 = 'value1' print obj1.attr1, obj2.attr1print obj1 is obj2

Output result:

Value1 value1
True

We can see that obj1 and obj2 are the same instance.


Python has many functions similar to _ init _.

_ Init _ is the class constructor.
_ Le _ ne _ is an operator function.
_ Le _ Yes <=
_ Ne _ Yes! =
Overloading these two functions is equivalent to overloading operators.

In python, how should I write the variables in the brackets _ init _ (), which respectively indicate what?

1. If you use _ init _ (self) in the class, there must be a self in the brackets.
This corresponds
_ Init _ (self): parameters after self. name = name must use the same
2. the other parameters in the brackets _ init _ (self) mean the same as your usual def af (id, title ).


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.