SoFunction
Updated on 2024-10-30

Example of a subclass inheriting the __init__ method of a parent class in python

preamble

Those of you who have written object-oriented code in Python may be interested in the __init__ The method is already very familiar,__init__method runs as soon as an object of the class is created. This method can be used to do some initialization of your object as you wish.

Attention:This name begins and ends with a double underscore.

Parent class A

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

Subclasses do not override__init__ , when instantiating a subclass, it automatically calls the parent class definition of the__init__

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

fulfillment

$python  
name: hello
B hello

But rewriting the__init__When you instantiate a child class, you don't call the parent class's already defined__init__

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

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

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

fulfillment

$python  
hi
B hello

In order to be able to use or extend the behavior of a parent class, it is best to show calls to the parent class'__init__methodologies

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

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

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

fulfillment

$python 
name: hello
hi
B hello

summarize

The above is all about python subclass inheritance parent class __init__ method, I hope that the content of this article on everyone's learning or work can bring some help, if there are questions you can leave a message to exchange.