class Parent():
def __init__(self, x):
self.x = x
print('init parent')
def hithere(self):
print('hey there')
print(self.x)
class Child(Parent):
def __init__(self, x):
self.x = x
super().hithere()
child = Child(3)这里我有一个父类和一个从父类继承的子类。如果我总是可以通过用继承的父类的名称替换它来做同样的事情,那么为什么我还需要super():
class Parent():
def __init__(self, x,y):
self.x = x
self.y = y
print('init parent')
def hithere(self):
print('hey there')
print(self.x)
class Child(Parent):
def __init__(self, x):
self.x = x
Parent.hithere(self)
child = Child(3)做同样的事情。
我的第二个问题是说抽象类不能有属性是正确的吗?如果Parent是一个抽象类,那么每当它的某个方法调用self (如hithere(self) )时,我需要用super().method(self)回传它。因此,这些属性实际上是Child的属性,只是恰好与要使用的父类具有相同的属性名称。
发布于 2019-05-05 07:54:10
这是一回事,但您应该使用super(),因为:
将来,如果您想要更改父类的名称,则不必更改每个实例的名称。
例如
Parent.hithere(self)
Parent.hithere1(self)
Parent.hithere2(self)现在,如果更改父类的名称,则必须更改每个实例的名称Parent。如果您要这样做,情况就不会是这样:
super().hithere1()
super().hithere2()
super().hithere3()我认为您的第二个问题是模棱两可的,但是您可以阅读有关抽象类here的更多信息。
发布于 2019-05-05 08:12:35
您几乎总是希望使用self.foo(),除非您正在编写覆盖Parent.foo的Child.foo方法。
如果您稍后编写了一个Child.hithere方法,则当前代码将不会使用它,这通常不是您想要的。
https://stackoverflow.com/questions/55987684
复制相似问题