Subclasses in python inherit instances of the parent class s method s 1en__

  • 2020-05-17 05:52:48
  • OfStack

preface

Those of you who have written object-oriented code using Python might be right __init__ The method is already very familiar ,__init__ The method runs as soon as one object of the class is created. This method can be used to do whatever initialization you want on your object.

Note: the name begins and ends with a double underscore.

The parent class A


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

Subclass does not override __init__ , instantiate the child class, will automatically call the parent class definition __init__


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

perform


$python lei2.py 
name: hello
B hello

But rewritten __init__ When a child class is instantiated, it does not call the parent class already defined __init__


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

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

if __name__=='__main__':
 b=B('hello')
 print b.getName()

perform


$python lei2.py 
hi
B hello

In order to be able to use or extend the behavior of the parent class, it is best to display the behavior of the calling parent class __init__ methods


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

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

if __name__=='__main__':
 b=B('hello')
 print b.getName()

perform


$python lei2.py
name: hello
hi
B hello

conclusion

This is all about the method of s 39en subclass inheriting s 40en__. I hope the content of this article can help you in your study or work. If you have any questions, please leave a message.


Related articles: