【问题标题】:Purpose of super() when class does not inherit类不继承时 super() 的用途
【发布时间】:2022-11-18 02:18:38
【问题描述】:

我在 realpython.com 中找到了一段关于 python super() 的代码,但我不明白 Rectangle 和 Triangle 中 super() 的用途是什么在里面如果两个类都没有父类(不继承)。

    class Rectangle:
        def __init__(self, length, width, **kwargs):
            self.length = length
            self.width = width
            super().__init__(**kwargs)

        def area(self):
            return self.length * self.width

    class Square(Rectangle):
        def __init__(self, length, **kwargs):
            super().__init__(length=length, width=length, **kwargs)

    class Triangle:
        def __init__(self, base, height, **kwargs):
            self.base = base
            self.height = height
            super().__init__(**kwargs)

        def tri_area(self):
            return 0.5 * self.base * self.height

    class RightPyramid(Square, Triangle):
        ...

【问题讨论】:

    标签: python-3.x inheritance


    【解决方案1】:

    这样,这些类可以使用多重继承,并且它们可能在编码时获取未知的祖先 - 调用super,传递他们可能获得的任何未知参数,确保他们在以这种方式使用时会很好地发挥作用。

    例如,假设这些形状用于表示创建具体的 3D 打印塑料对象。

    class Print3D:
        def __init__(self, *, filament="PLA", **kw):
             self.filament=filament 
             print("Print3D part initialized")
             super().__init__(**kwargs)
    

    现在可以做到:

    class PrintedSquare(Square, Print3D):
        pass
    
    mysquare = PrintedSquare(length=20, filament="PVC")
    
    

    一切都会正常进行。

    【讨论】:

      猜你喜欢
      • 2011-04-09
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多