In python, _ init _, _ new _, and _ call _ summary __init ___ new __

Source: Internet
Author: User

In python, _ init _, _ new _, and _ call _ summary __init ___ new __
This article mainly introduces _ init _, _ new _, and _ call _ in python. For more information, see

1. _ new _ (cls, * args, ** kwargs) is called when an object is created, and an instance of the current object is returned. Note: The first parameter here is cls, that is, the class itself.
2. _ init _ (self, * args, ** kwargs) is called after an object is created. It initializes some instances of the current object and has no return value, that is, after _ new _ is called, it is initialized Based on the returned instance. Note that the first parameter here is self, which is the object itself. [note the difference with new]
3. _ call _ (self, * args, ** kwargs) if the class implements this method, it is equivalent to using this type of object as a function, which is equivalent to reloading the brackets operator.
 

Take a look at the specific example:

Copy the Code as follows:
Class O (object ):

Def _ init _ (self, * args, ** kwargs ):
Print "init"
Super (O, self). _ init _ (* args, ** kwargs)

Def _ new _ (cls, * args, ** kwargs ):
Print "new", cls
Return super (O, cls). _ new _ (cls, * args, ** kwargs)

Def _ call _ (self, * args, ** kwargs ):
Print "call"

Oo = O ()
Print "________"
Oo ()


Printed:
Copy the Code as follows:
New
Init
________
Call
For example, if Python Singleton (Singleton mode) is implemented, can we just reload some _ new _ methods?
Copy the Code as follows:
Class Singleton1 (object ):
"Reload the new method """
Def _ new _ (cls, * args, ** kwargs ):
If not "_ instance" in vars (cls ):
Cls. _ instance = super (Singleton1, cls). _ new _ (cls, * args, ** kwargs)
Return cls. _ instance

Can we reload the _ init _ method? Obviously not. Because the _ init _ method was called before, an object has been generated and the singleton mode cannot be implemented.

========================================================== ===

Note 1, _ Init _ is not equivalent to the constructor in C,Instance constructedCome out.

12345 class A(object):    def __init__(self,name):        self.name=name    def getName(self):        return 'A '+self.name

When we execute

1 a=A('hello')

Can be understood

12 a=object.__new__(A)A.__init__(a,'hello')

That is, _ init _ initializes the instantiated object.

Note 2Subclass canDo not override_ Init __, when instantiating a subclass,Will be called automatically_ Init _ defined in the superclass __

1234567 class B(A):    def getName(self):        return 'B '+self.name if __name__=='__main__':    b=B('hello')    print b.getName()

However, ifRewritten_ Init __, when instantiating a subclassIt will not be called implicitly._ Init _ defined in the superclass __

123456789 class C(A):    def __init__(self):        pass    def getName(self):        return 'C '+self.name if __name__=='__main__':    c=C()    print c.getName()

The error "AttributeError: 'C' object has no attribute 'name'" will be reported, soIf _ init __is overwritten, it is best to explicitly call the _ init _ method of the superclass to be able to use or extend the behavior in the superclass.

123456789 class C(A):    def __init__(self,name):        super(C,self).__init__(name)    def getName(self):        return 'C '+self.name if __name__=='__main__':    c=C('hello')        print c.getName()

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.