Cia*_*lsh 1 python inheritance
我在Python中理解继承有一点困难.我的印象是,当Class B从Class A它继承时,继承了在A中初始化的所有值.我已经编写了一个例子来证明我的意思:
Class A():
def __init__(self,parameter):
self.initialize_parameter=4*parameter
Class B(A):
def __init__(self):
pass
def function(self,another_parameter):
return self.initialize_parameter*another_parameter
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,请致电:
B_instance=B()
print B_instance.function(10)
Run Code Online (Sandbox Code Playgroud)
返回AttributeErrorB类没有的说法self.initialized_parameter
所以我的问题是,我是否必须手动将所有初始化从A复制并粘贴到B或者是否可以在B中使用它们而不调用A类本身?(我希望这很清楚).
如果要使用超类构造函数中的行为,则应该不要覆盖它:
Class B(A):
def function(self,another_parameter):
return self.initialize_parameter*another_parameter
Run Code Online (Sandbox Code Playgroud)
或者,如果要扩展可以使用的初始化行为 super()
Class B(A):
def __init__(self, parameter)
super(B, self).__init__(2*parameter)
def function(self,another_parameter):
return self.initialize_parameter*another_parameter
Run Code Online (Sandbox Code Playgroud)
在Python 3 super()中不需要显式参数(super().__init__()).
这种一般覆盖行为super()适用于所有方法,而不仅仅是构造函数.