2015-01-10 46 views
0

我創建了一個類Rectangle並嘗試保存到一個模塊。在python 2.7.6中運行模塊?

輸出:

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 

另一個文件來運行測試矩形模塊:

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() 
+1

好的..那麼問題是什麼? – thefourtheye

+0

回溯(最近通話最後一個): 文件「/用戶/ Dropbox的/使用Python 3/* PY」,2號線,在 從矩形進口矩形 導入錯誤:沒有模塊名爲矩形 –

+0

是包含了Python文件定義名爲'Rectangle.py'的'Rectangle'類?該文件是否在你的Python路徑中,即在'sys.path'列表中的一個目錄中? –

回答

-1

試試這個裏面test.py,

進口sys

sys.path.append(「Rectangle類模塊路徑」)

進口「Rectangle類模塊」

+0

模塊的名稱中不能有空格。 – martineau

0

問題不在於你的代碼,但你的文件命名並設置在目錄。由於您的問題目前不包含有關您的文件的名稱和目錄的信息,因此我們無法爲您提供更多幫助。至少,Rectangle類應該位於名爲Rectangle.py的文件中,並且該文件必須位於當前目錄中,或者位於PYTHONPATH的目錄中。也可以有一個名爲Rectangle的目錄,然後它需要包含一個文件__init__.py,該文件可能爲空,或者包含模塊範圍的Python代碼。

0

固定編碼:

從Exercise0701進口矩形

自從我保存的文件名是Exercise0701.py,它不能在計算機找到矩形的文件名。

我犯了錯誤。

謝謝大家。

+0

請將此(或其他答案,如果您喜歡)標記爲已接受,以便此問題不再出現爲未解決問題。謝謝。 – tripleee