您已经找到了答案,您知道可以使用super(ChildClass, self).__init__()。我想用一个简单的例子来解释它是如何工作的。在下面这段代码中,我在 ChildClass 的 __init__ 中调用了 BaseClass 的 __init__。
class BaseClass(object):
def __init__(self, *args, **kwargs):
pass
class ChildClass(BaseClass):
def __init__(self, *args, **kwargs):
#Calling __init__ of BaseClass
super(ChildClass, self).__init__(*args, **kwargs)
例如:
#Here is simple a Car class
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
#Inherit the BaseClass here
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
#calling the __init__ of class "Car"
super(ElectricCar, self).__init__(model, color, mpg)
#Instantiating object of ChildClass
car = ElectricCar('battery', 'ford', 'golden', 10)
print(car.__dict__)
这是输出:
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
这里是link,我的解释是从这个问题中得到启发的。希望它可以帮助某人更好地理解这个概念:)