Python shell没有显示错误,但程序不运行

3
我是一名有用的助手,可以为您翻译文本。

我写了这个程序来学习面向对象编程的基础知识。当我在Python Shell中从IDLE运行此程序时,它没有显示任何错误,但也没有打印任何内容...我不确定如何找出我的错误。

以下是我的代码:

class Shapes(object):
    def __init__(self, width, length):
        object.__init__(self)
        self.setWidth(width)
        self.setLength(length)

    def getWidth(self):
        return self.width

    def setWidth(self, width):
        if (width <= 0):
            width = 5
        else:
            width = self.width

    def getLength(self):
        return self.length

    def setLength(self, length):
        if (length <= 0):
            length = 10
        else:
            length = self.length

class Rectangle(Shapes):
    def __init__(self, area, perimeter):
        Shapes.__init__(self, length, width)

    def getArea(length, width):
        return length * width

    def getPerimeter(length, width):
        return (length * 2) + (width * 2)

    def getStats(self):
        print("Area: {}".format(self.getArea()))
        print("Perimeter: {}".format(self.getPerimeter()))
        print("Length: {}".format(self.getLength()))
        print("Width: {}".format(self.getWidth()))


def main():
    print("Rectangle a: ")
    a = Rectangle(5, 7)
    print("Area:          {}".format(a.area))
    print("Perimeter:     {}".format(a.perimeter))

    print( " ")
    print("Rectangle b: ")
    b = Rectangle()
    b.width = 10
    b.height = 20
    print(b.getStats())

以下是Shell正在做的事情,如果您想查看:

http://imgur.com/DxyUZyY

我做错了什么,如何纠正?


这是行不通的: def init(self, area, perimeter): Shapes.init(self, length, width) - Eric Levieil
1个回答

2
你从未调用主函数。与C语言不同,main函数会自动执行,在Python中你必须显式地调用它;主函数没有任何特殊意义,只是Python中的另一个函数。
因此在代码末尾写上:
```python if __name__ == '__main__': main() ```
main()

运行后,你会看到像@Eric在评论中指出的错误,还有很多其他错误。
你当前的代码存在许多问题,以下是其中一些问题的列表:
  1. object.__init__(self) doesn't do anything
  2. self.setWidth(width) calls the method, but the setWidth method tries to set to a variable that hasn't been declared yet.

    • So this needs to be corrected to

      def setWidth(self, width):
          if (width <= 0):
              width = 5
          else:
              width = width # and not self.width
      
  3. The above is true for setLength as well.

  4. Since you are using these methods to set and get values, you should look into using @property.
  5. Shapes.__init__(self, length, width) is not the correct call.
    • You need to look into super
    • length, width are not defined here.

哦天啊,非常感谢!我在执行时遇到了一些错误。你有什么想法可以帮我解决吗?回溯(最近的调用最先): 文件“C:/Rectangle.py”,第55行,在<module>中 main() 文件“C:/Rectangle.py”,第44行,在main中 a = Rectangle(5, 7) 文件“C:/Rectangle.py”,第27行,在__init__中 Shapes.init(self, length, width) NameError: name 'length' is not defined - Joseph Wagner
@JosephWagner,请检查我回答的编辑。SO的格式是每个帖子一个问题,所以我不认为我可以回答更多的后续问题。如果有帮助,请不要忘记接受答案,以标记为已解决 :) - Anshul Goyal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接