在python 2.7.6中运行模块?

时间:2015-01-10 07:14:23

标签: python python-2.7 module

我创建了一个类Rectangle并尝试保存到模块。

输出:

Traceback (most recent call last):
File "/Users/Dropbox/using Python 3/test.py", line 2, in <module>
from Rectangle import Rectangle
  ImportError: No module named Rectangle

我的代码:

import math
class Rectangle:
    def __init__(self, width = 1 , height = 2):
        self.width = width
        self.height = height

    def getPerimeter (self):
        return (self.width + self.height) * 2

    def getArea (self):
        return self.width * self.height

    def setSides( self, width, height):
        self.width = width
        self.height = height

运行另一个文件以测试Rectangle模块:

from Rectangle import Rectangle

def main ():
    Rectangle1 = Rectangle(4, 40)
    print  "The area  of the rectangle,", Rectangle1.width, "is width and", Rectangle1.height, "is height, are", Rectangle1.getArea()
    print  "The perimeter of the rectangle,", Rectangle1.width, "is width and", Rectangle1.height, "is height, are", Rectangle1.getPerimeter()

    Rectangle2 = Rectangle(3.5, 35.7)
    print  "The area of the rectangle,", Rectangle2.width, "is width and", Rectangle2.height, "is height, are", Rectangle2.getArea()
    print  "The perimeter of the rectangle,", Rectangle2.width, "is width and", Rectangle2.height, "is height, are", Rectangle2.getPerimeter()

main ()

3 个答案:

答案 0 :(得分:0)

问题不在于您的代码,而在于您的文件在目录中的命名和排列方式。因为您的问题目前不包含有关您的文件命名的信息以及它们所在的目录,所以我们无法为您提供更多帮助。 Rectangle类至少应位于名为Rectangle.py的文件中,并且它必须位于当前目录中,或位于PYTHONPATH上的目录中。也可以有一个名为Rectangle的目录,然后需要包含一个文件__init__.py,该文件可能为空,或者包含模块范围的Python代码。

答案 1 :(得分:0)

固定代码:

来自Exercise0701的

导入矩形

由于我保存的文件名是Exercise0701.py,因此无法在计算机中找到Rectangle的文件名。

我犯了错误。

谢谢大家。

答案 2 :(得分:-1)

在test.py,

中试试

导入sys

sys.path.append(&#34; Rectangle类模块路径&#34;)

导入&#34;矩形类模块&#34;