Rahul Dev Mishra Rahul Dev Mishra - 1 month ago 13
Python Question

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

I have three classes which extend each other.

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


I have a simple question here. I want to default the values of lineWidth and lineColor and set it to the values that are given in the GeometricObject class. If I don't default it, then I would have to then always pass three parameters to the Polygon class constructor. And this is what I am trying to avoid. If lineWidth and lineColor are not passed then it should default the values.

Any suggestions ?

Answer
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

I've added calls to the super constructor which is the main thing you were missing. In your code only one __init__ gets called. This also means I had to add the missing color parameter to Polygon.

If no falsy values are allowed in Polygon, then the if statements can be replaced with:

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