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

问题描述:

我有三个相互扩展的类。Python:如何在Child类的构造函数参数中获取父类的参数

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没有通过,那么它应该默认值。

有什么建议吗?

+0

旁注:

如果没有falsy值被允许在Polygon,那么if语句可以被替换为什么'GeometricObject'用不了'lineWidth'和'lineColor'作为参数?为什么只有它的孙子才能定制?另外,在Python中你应该使用'snake_case',而不是'camelCase'。 –

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

self.lineColor = lineColor or self.lineColor 
    self.lineWidth = lineWidth or self.lineWidth 
+0

我不明白解决方案。 “颜色”究竟是干什么的? –

+0

@RahulDevMishra进入超级构造函数,即“Shape”的构造函数。如何设置颜色?尝试运行你的代码加上'cornerPoints = []; p =多边形(角点);打印(p.fillColor)'。你认为会发生什么? –