Python:如何从派生类的实例对象调用super()

时间:2019-03-23 17:27:27

标签: python-3.x oop

我想通过以下方式从派生类的实例对象的B调用super方法:

class B:
    pass

class A(B):
    pass

a_object = A()
a_object.super().__init__()

我收到以下错误:

AttributeError: 'A' object has no attribute 'super'

是否可以通过这种方式调用超级方法?

2 个答案:

答案 0 :(得分:1)

我找到了一种使用方法:

super(A, a_object).__init__()

答案 1 :(得分:1)

找到答案后,您就可以使用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的问题,我的解释从中得到启发。希望它可以帮助人们更好地理解这个概念:)