【问题标题】:Python: How to call super() from instance object of the derived class [duplicate]Python:如何从派生类的实例对象调用 super() [重复]
【发布时间】:2019-03-23 17:27:27
【问题描述】:

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

class B:
    pass

class A(B):
    pass

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

我收到以下错误:

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

有没有办法可以用这种方式调用超级方法?

【问题讨论】:

    标签: python-3.x oop


    【解决方案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,我的解释是从这个问题中得到启发的。希望它可以帮助某人更好地理解这个概念:)

    【讨论】:

      【解决方案2】:

      我找到了一种使用方法:

      super(A, a_object).__init__()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-09
        • 1970-01-01
        • 1970-01-01
        • 2016-07-06
        相关资源
        最近更新 更多