The following describes three special methods in Python: _ new _, _ init _, and _ call _, __new ____ init __

Source: Internet
Author: User

The following describes three special methods in Python: _ new _, _ init _, and _ call _, __new ____ init __

_ New __: create an object. It is a static method. The first parameter is cls. (Think too. It's impossible to be self. The object has not been created yet. Where is self)
_ Init _: object initialization, which is an instance method. The first parameter is self.
_ Call _: the object can be called. Note that it is not a class but an object.

Initialization is available only after creation. First _ new __, then _ init __.
The above is not easy to understand. Let's look at the example.

1. For _ new __

class Bar(object):   pass  class Foo(object):   def __new__(cls, *args, **kwargs):     return Bar()  print Foo() 

As you can see, the output is a Bar object.

The _ new _ method is not required in the class definition. If it is not defined, object. _ new _ is called by default to create an object. If it is defined, it is override. You can use M to create an object.
Smart readers may think that, since _ new _ can create a m object, I will do some operations here, and the same object will be returned every time I create an object, isn't it the singleton mode? That's right. You can watch the elegant python-single-instance mode.
When defining the singleton mode, because the custom _ new _ loads the _ new __of the parent class, you must explicitly call the _ new __, object. _ new _ (cls, * args, ** kwargs), or use super ()., Otherwise, it is not the original extend instance, but the original Instance.

2. For _ init __

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.

3. For _ call __
An object can simulate the behavior of a function by providing the _ call _ (slef, [, * args [, ** kwargs]) method. If an object x provides this method, it can be used like a function, that is, x (arg1, arg2 ...) it is equivalent to calling x. _ call _ (self, arg1, arg2 ). The simulated function object can be used to create an anti-function (functor) or proxy ).

Class Foo (object): def _ call _ (self): pass f = Foo () # class Foo can call f () # object f can call

In summary, in Python, the class behavior is like this, __new _, _ init _, _ call _, and other methods are not required, and are called by default, if you have defined it as override, you can use M. Since it is override, it is usually explicitly called for compensation to achieve the purpose of extend.
This is also why the strange behavior of "clearly defining def _ init _ (self, * args, ** kwargs) and object initialization" appears. (Note: Here _ init _ has less underline, because _ init _ is not required, so no error is reported here, but as a new method _ init __)

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.