In python, subclass inherits the _ init _ Method Instance of the parent class, and python _ init _

Source: Internet
Author: User

In python, subclass inherits the _ init _ Method Instance of the parent class, and python _ init _

Preface

If you have written object-oriented code using Python __init__ The method is very familiar.,__init__Method runs immediately when an object of the class is created. This method can be used to initialize your object.

Note:The start and end of the name are double underscores.

Parent Class

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

Subclass not override__init__ Automatically calls__init__

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

Run

$python lei2.py name: helloB hello

But it is rewritten.__init__If the subclass is instantiated, the defined__init__

class A(object): def __init__(self, name):  self.name=name  print "name:", self.name def getName(self):  return 'A ' + self.nameclass B(A): def __init__(self, name):  print "hi"  self.name = name def getName(self):  return 'B '+self.nameif __name__=='__main__': b=B('hello') print b.getName()

Run

$python lei2.py hiB hello

In order to use or extend the behavior of the parent class, it is better to display the behavior that calls the parent class__init__Method

class A(object): def __init__(self, name):  self.name=name  print "name:", self.name def getName(self):  return 'A ' + self.nameclass B(A): def __init__(self, name):  super(B, self).__init__(name)  print "hi"  self.name = name def getName(self):  return 'B '+self.nameif __name__=='__main__': b=B('hello') print b.getName()

Run

$python lei2.pyname: hellohiB hello

Summary

The above is all about how python subclass inherits the _ init _ method of the parent class. I hope this article will help you in your learning or work, if you have any questions, you can leave a message.

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.