Python:如何在子 class 构造函数参数中获取父 class 参数

Python: How to get Parent's class parameters in Child class constructor arguments

我有三个 class 相互延伸。

class GeometricObject:
    def __init__(self):
        self.lineColor = 'black'
        self.lineWidth = 1

    def getColor(self):
        return self.lineColor

    def getWidth(self):
        return self.lineWidth

class Shape(GeometricObject):
    def __init__(self, color):
        self.fillColor = color

class Polygon(Shape):
    def __init__(self, cornerPoints, lineWidth = ?, lineColor = ?):
        self.cornerPoints = cornerPoints
        self.lineColor = lineColor
        self.lineWidth = lineWidth

我有一个简单的问题。我想默认 lineWidth 和 lineColor 的值并将其设置为 GeometricObject class 中给出的值。如果我不默认它,那么我将不得不始终将三个参数传递给 Polygon class 构造函数。而这正是我要避免的。如果未传递 lineWidth 和 lineColor,则应使用默认值。

有什么建议吗?

class GeometricObject:
    def __init__(self):
        self.lineColor = 'black'
        self.lineWidth = 1

        # getters

class Shape(GeometricObject):
    def __init__(self, color):
        super().__init__()
        self.fillColor = color

class Polygon(Shape):
    def __init__(self, cornerPoints, color, lineWidth=None, lineColor=None):
        super().__init__(color)
        self.cornerPoints = cornerPoints
        if lineColor is not None:
            self.lineColor = lineColor
        if lineWidth is not None:
            self.lineWidth = lineWidth

我已经添加了对超级构造函数的调用,这是您缺少的主要内容。在您的代码中,只有一个 __init__ 被调用。这也意味着我必须将缺少的 color 参数添加到 Polygon.

如果 Polygon 中不允许使用假值,则 if 语句可以替换为:

    self.lineColor = lineColor or self.lineColor
    self.lineWidth = lineWidth or self.lineWidth