我在 Python 覆盖 class 继承方面遇到问题?

I have a problem in Python Overriding class inheritance?

我有 parent class 形状

class Shape:
    def __init__(self):
        pass

    def getArea(self):
        raise Exception('Override the method getArea')

    def printArea(self):
        if not hasattr(self, 'name'):
            raise Exception('Your class is still invalid.')

        print("The area of the current", self.name.lower(), "is", self.getArea())

我创建了一个覆盖 getArea()

的 class 三角形
# Sample Triangle class
class Triangle(Shape):
    def __init__(self, b, h):
        super().__init__()
        self.name = 'Triangle'
        self.b = b
        self.h = h

    def getArea(self):
        return 0.5 * self.b * self.h

与三角形相同

class Parallelogram(Shape):
    def __init__(self, w, h):
        super().__init__()
        self.name = 'Parallelogram'
        self.w = w
        self.h = h

    def getArea(self):
        return self.w * self.h

矩形parent应该是平行四边形

class Rectangle(Parallelogram):
    def __init__(self, w, h):
        self.name = 'Rectangle'
        self.w = w
        self.h = h

这是我用一个参数实例化 Square class 的问题,parent 应该是 Rectangle Square 构造函数参数应该只有 selfw

class Square(Rectangle):
    def __init__(self, w):
        self.name = 'Square'
        self.w = w 
square = Square(11)
square.printArea()

在这里覆盖函数时出现错误

The Square class Has no Attribute name "h"

方块的预期输出应该是:

The area of the current square is 121

覆盖 Square 中的 getArea

def getArea(self):
    return self.w ** 2

问题是您需要为所有子class 执行super.__init__ 并让父class 处理它知道的实例变量的赋值。例如 Rectangle 不应该设置父级 classes w 和 h,它不知道父级是否对这些值进行了一些处理。而且由于 Square 没有重新实现 getArea 它最好调用 super 的 init 来正确设置变量。

以下是您的程序,其中对矩形和正方形进行了 super().__init__ 修改。

class Shape:
    def __init__(self):
        pass

    def getArea(self):
        raise Exception('Override the method getArea')

    def printArea(self):
        if not hasattr(self, 'name'):
            raise Exception('Your class is still invalid.')

        print("The area of the current", self.name.lower(), "is", self.getArea())

# Sample Triangle class
class Triangle(Shape):
    def __init__(self, b, h):
        super().__init__()
        self.name = 'Triangle'
        self.b = b
        self.h = h

    def getArea(self):
        return 0.5 * self.b * self.h

class Parallelogram(Shape):
    def __init__(self, w, h):
        super().__init__()
        self.name = 'Parallelogram'
        self.w = w
        self.h = h

    def getArea(self):
        return self.w * self.h

class Rectangle(Parallelogram):
    def __init__(self, w, h):
        super().__init__(w, h)
        self.name = 'Rectangle'

class Square(Rectangle):
    def __init__(self, w):
        super().__init__(w, w)
        self.name = 'Square'

square = Square(11)
square.printArea()

这个有用吗?

class Square(Rectangle):
    def __init__(self, w):
        self.name = 'Square'
        self.w = w
        self.h = w

编辑:太慢了!没看评论!