Python: How to call super() from instance object of the derived class
本问题已经有最佳答案,请猛点这里访问。
我想用以下方式从派生类的实例对象的b调用super方法:
1 2 3 4 5 6 7 8 | class B: pass class A(B): pass a_object = A() a_object.super().__init__() |
我得到以下错误:
1 | AttributeError: 'A' object has no attribute 'super' |
有没有一种方法可以用这种方式调用super方法?
因为你已经找到了答案,你知道你可以使用
1 2 3 4 5 6 7 8 | 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) |
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #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__) |
输出结果如下:
1 | {'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'} |
这是一个问题的链接,我的解释就是从这个问题中得到启发的。希望它能帮助人们更好地理解这个概念:)
我找到了一种方法:
1 | super(A, a_object).__init__() |