__new__ in Python and how to use it

Source: Internet
Author: User

The difference between __new__ and __init__

__new__ is a seldom-used function in Python's object-oriented language, and is more used by the __init__ function. For example:

Class Book (object): Def __init__ (self, title): Super ("book, Self"). __init__ (self) self.title = title# Defin e a bookb = Book ("The Django book") Print B.title

The above is the OOP language of the entry code, a cursory look at __init__ and Java in the same constructor, in fact, it does not actually calculate the upper constructor. __new__ is the way to create an instance.

According to the official documentation:

    • __init__ is called when the instance object is created, and then sets some initial values for the object properties.

    • __new__ is called before the instance is created, because its task is to create an instance and then return to that instance, which is a static method.

That is, __new__ is called before __init__, __new__ 's return value (instance) is passed to the first parameter of the __init__ method, and then __init__ sets some parameters to the instance.

Class Book (object): Def __new__ (CLS, title): print ' __new__ ' return Super (book, CLS). __new__ (CLS)        def __init__ (self, title): print ' __init__ ' super ("book, Self"). __init__ (self) self.title = title b = Book ("The Django book") Print B.title

The result of the above execution:

__new____init__the Django Book
__NEW__ 's application Scenario

The official documentation indicates two uses of the __new__ method.

Allow inheritance of immutable types (str,int, tuple)

There are more examples of this, the online search of the examples are basically theoretical, practical usage is not very common.

use in Metaclass

Metaclass is a python syntax sugar bar, simply by which you can dynamically generate or change the definition of a class.

A more practical example is how to access the current request requests when the Django Admin form validates. Stackflow's links are as follows:

http://stackoverflow.com/questions/1057252/ how-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clean-met/6062628#6062628

The first thought is to pass the request to the past, which can be used in the clean method.

Class MyForm (forms. Modelform): Def __init__ (self, *args, **kwargs): Self.request = Kwargs.pop (' request ') Super (MyForm, self) . __init__ (*args, **kwargs) def clean (self): #这里可以得到self. Request Information Pass

In the usual view, call with the following code:

f = MyForm (Request. POST, Request=request)

But not when customizing the Modeladmin, because the admin only provides get_form this method, the return value is the class object, not the instance object

Get_form (self, request, *args, **kwargs): # This line of code is wrong # return MyForm (request=request) return MyForm # OK

Use the __new__ method to solve this problem.

def get_form (self, request, *args, **kwargs): Class Modelformmetaclass (MyForm): Def __new__ (CLS, *args, **kwargs ): kwargs[' request '] = Request return MyForm (*args, **kwargs) return Modelformmetaclass

So what happens, Add_view's calling code is as follows:

Def add_view (self, request, form_url= ",  extra_context=none)"          modelform = self.get_form (Request)     if  request.method ==  ' POST ':         form = modelform ( Request. Post, request. FILES)          #可以获取request参数          # print form.request        if form.is_valid ():             pass         else:            pass     ELSE:       &NBSP, ..... (calculation initial)         form = modelform (initial=initial)

Analysis: Form = Modelformmetaclass (Request. POST, request. FILES), according to the usual understanding, the right side should return an instance of Modelformmetaclass, because the __new__ function was overridden, the parent class function was not called, but a MyForm instance with the request parameter was returned, and then called __init __ function, so the last Modelformmetaclass () Return is also the instance, and the left side needs to be the MyForm instance object. So the function of the __new__ is to create an instance.

Note: Metaclass It reduces the readability of the code, and there are alternatives that are not recommended for use in projects. If you are interested, you can refer to this .

References

__new__ and __init__ (French edition)

http://sametmax.com/la-difference-entre-__new__-et-__init__-en-python/

Python-always-use-new-instead-of-init

Http://stackoverflow.com/questions/3131488/python-always-use-new-instead-of-init

Metaclasses in Python

http://xiaocong.github.io/blog/2012/06/12/python-metaclass/

How-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clean-met

http://stackoverflow.com/questions/1057252/ how-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clean-met/6062628#6062628




__new__ in Python and how to use it

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.