目的:此文的目的在于理解Python继承过程中的__init__方法,谨作小记
1.子类继承父类时,如果__init__方法被重写,可以使用super函数调用父类的__init__方法,否则被改写的__init__方法会覆盖原有的自动继承的__init__方法。
2.类的继承,就是子类继承除了构造函数之外的所有的东西,__init__方法不是构造方法(函数)
3.子类继承父类时,__init__方法被自动继承,并在创建实例时,自动调用。
-
-
class A(object):
-
def __init__(self,message):
-
self.message=message;
-
#B inherits from A without writing the function __init__,It just define a function called getmessag
-
#e,So,the init will be inherited, the __init__ will be inherted by B by default
-
# if you create b using B, the init will work and the "message" will be return.
-
-
class B(A):
-
def getmessage(self):
-
return self.message
-
-
b=B('B')
-
-
print b.getmessage()
-
-
-
#C inherit from A and rewrite the __init__function,
-
#So the message will not be initialized and the c.getmessage will not work.
-
-
#class C(A):
-
# def __init__(self, message):
-
# pass
-
# def getmessage(self):
-
# return self.message
-
-
-
#c=C('C')
-
-
#print c.getmessage()
-
-
#So the D inherit from A and using a method super( type, obj ), this can be unde
-
#rstood like below, the super method find the D `s base class and change the self
-
#to its super class, then using the "super(D,self)
-
class D(A):
def __init__(self,message):
super(D,self).__init__(message)
def getmessage(self):
return self.message
d=D('D')
print d.getmessage()
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29757574/viewspace-2086179/
,如需转载,请注明出处,否则将追究法律责任。