Objective
Students who have used python to write object-oriented code may be familiar with __init__
methods that ,__init__
run immediately when an object in a class is created. This method can be used to do some of the initialization you want for your object.
Note: This name starts and ends with a double underline.
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 is not overridden __init__
, the parent class definition is automatically invoked when the subclass is instantiated.__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
When overridden, __init__
instantiates a subclass and does not call the parent class that has already been 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 show methods that invoke the parent class __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):
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
Summarize
The above is about the Python subclass inherits the parent class the whole content of the __init__ method, hope this article's content to everybody's study or work can bring certain help, if has the question everybody may the message exchange.