Python:如何在Child类构造函数参数中获取Parent的类参数

时间:2016-11-09 23:29:06

标签: python python-3.x turtle-graphics

我有三个相互延伸的课程。

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类中给出的值。如果我没有默认它,那么我必须总是将三个参数传递给Polygon类构造函数。这就是我想要避免的。如果未传递lineWidth和lineColor,则应默认值。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

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