__init__ () method in Python note points

Source: Internet
Author: User

This article goes from https://www.cnblogs.com/zyxstar2003/archive/2011/03/21/1989954.html

1, __init__ is not equivalent to the constructor in C #, when it is executed, instance has been constructedOut.
1 class A (object): 2     def __init__ (self,name): 3         Self.name=name4     def  getName (self):5          return'+self.name

When we execute

1 a=a ('hello')

, it can be understood as

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

That is, the __init__ function is to initialize the object after it has been instantiated.

2, sub-class can be do not rewrite__init__, when instantiating subclasses, is automatically called__init__ defined in the superclass
1 classB (A):2     defGetName (self):3         return 'B'+Self.name4  5 if __name__=='__main__':6B=b ('Hello')7     PrintB.getname ()

However, if __init__ is overridden and the subclass is instantiated, the defined __init__ in the superclass are not implicitly called again

1 classC (A):2     def __init__(self):3         Pass4     defGetName (self):5         return 'C'+Self.name6  7 if __name__=='__main__':8C=C ()9     PrintC.getname ()

It will be reported "Attributeerror: ' C ' object has no attribute ' name '" error, so if __init__ is overridden, in order to be able to use or extend the behavior in the superclass, it is best to explicitly call the __init__ method of the Super class

1 classC (A):2     def __init__(self,name):3Super (C,self).__init__(name)4     defGetName (self):5         return 'C'+Self.name6  7 if __name__=='__main__':8C=c ('Hello')    9     PrintC.getname ()

__init__ () method in Python note points

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.