首页 > 解决方案 > 如何用 Python 解决这个继承问题?

问题描述

在以下用 Python 编写的脚本中,我想做的是计算圆形、正方形和矩形的面积。其中,我想实现从 square.py 到 rectangle.py 的继承。但是,我的继承实现失败了,需要一些帮助来解决这个问题。

当我试图计算一个矩形的面积时,我收到了以下错误信息。

Traceback (most recent call last):
  File "script.py", line 28, in <module>
    print(rectangle.sqArea())
  File "/home/yosuke/Dropbox/Coding_dir/Python/Originals/OOP/Mathmatics/testdir2/rectangle.py", line 8, in sqArea
    return self.length * self.height
AttributeError: 'Rectangle' object has no attribute 'length'

脚本.py

from circle import Circle
from square import Square
from rectangle import Rectangle

category = {1:"Shapes", 2:"DST"}
    for k,v in category.items():
    print(k, v)
catNum = int(input("Type a category by number>> "))
    if catNum == 1:
        print("You chose shapes")
        shapeDict = {1:"Circle", 2:"Square"}
    for k,v in shapeDict.items():
        print(k, v)
    shapeNum = int(input("Select a shape by number>> "))
    if shapeNum == 1:
        radius = int(input("type a number>> "))
        circle1 = Circle(radius)
        print(circle1.cirArea())

    if shapeNum == 2:
        length = int(input("Type the length>> "))
        square = Square(length)
        print(square.sqArea())

        print("Let's try rectangle too")
        height = int(input("Type the height>> "))
        rectangle = Rectangle(height)
        print(rectangle.sqArea())


    if catNum == 2:
        print("Not yet finished!")

圈子.py

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def cirArea(self):
        return self.radius * self.radius * 3.14

正方形.py

class Square:
    def __init__(self, length):
        self.length = length

    def sqArea(self):
        return self.length * self.length

矩形.py

from square import Square

class Rectangle(Square):
    def __init__(self, height):
        self.height = height

    def sqArea(self):
        return self.length * self.height

标签: pythonpython-3.xoopinheritancepython-3.7

解决方案


你的矩形的构造函数只接收一个高度,它只设置它的高度属性。它没有长度。

像这样的东西可以在矩形中起作用:

def __init__(self, length, height):
    super().__init__(length)
    self.height = height

但是你的课很奇怪。长方形不是正方形,正方形是长方形。因此,如果有的话,继承应该朝另一个方向工作。

但我认为你很快就会遇到问题。事实证明,面向对象编程并不能很好地模拟这类事情,实际上不同形状之间没有太多共享。


推荐阅读