The __new__ () method in Python

Source: Internet
Author: User

First look at the definition of the __new__ () method in the object class:

Class object:    @staticmethod # known case of __new__    def __new__ (CLS, *more): # Known special case of Object.__new_ _        "" "t.__new__ (S, ...)-A new object with type S, a subtype of T" ""        Pass

Object defines the __new__ () method as a static method, and at least one parameter needs to be passed CLS,CLS represents the needThe instantiated class, which is automatically provided by the Python interpreter when instantiated.

Let's look at the implementation of the __NEW__ () method in the following class:

Class Demo (object):    def __init__ (self):        print ' __init__ () called ... '    def __new__ (CLS, *args, **kwargs):        print ' __new__ ()-{CLS} '. Format (CLS=CLS)        return object.__new__ (CLS, *args, **kwargs) if __name__ = = ' __main__ ' :    de = Demo ()


__new__ ()-<class ' __main__. Demo ' >__init__ () called ...

When the object is instantiated, the __new__ () method is called before the call to __init__ () is initialized.

__NEW__ () must have a return value that returns an instantiated instance, and it is important to note that you can return an instance of the parent class __new__ (), or you can directly back an instance of Object __new__ ().

__init__ () has a parameter, self, which is the instance returned by __new__ (), and __init__ () can perform some other initialization action on the basis of __new__ (), and __init__ () does not need a return value.

if __new__ () does not return correctly Current class CLS instance, the __init__ () will not be called, even if it is an instance of the parent class.

We can compare the class to the manufacturer, the __new__ () method is the pre-purchase of raw materials, __init__ () method is on the basis of raw materials, processing, the initialization of commodity links.

In the actual application process, we can use this:

Class Lxmldocument (OBJECT_REF):    cache = Weakref. Weakkeydictionary ()    __slots__ = [' __weakref__ ']    def __new__ (CLS, Response, Parser=etree. Htmlparser):        cache = Cls.cache.setdefault (response, {})        if parser not in cache:            obj = object_ref.__new__ ( CLS)            Cache[parser] = _factory (response, parser)        return Cache[parser]

The use of the __new__ () method in this class is to check for the presence of the object in the cache before initializing it, to return the cached object directly if it exists, and to put the object in the cache for the next use if it does not exist.

The __new__ () method in Python

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: 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.