2016-08-15 78 views
-3

我有兩個文件,我想從另一個文件中導入一個類。如何從其他.py文件中調用一個.py文件中存在的函數?

文件one.py

class One: 
    def printNumber(self, a): 
     print (a) 

和文件two.py

#import One # gives error no module named One 
#import one # gives error no module named one 

class Two: 
    # Here I want to call printNumber method from one.py 
+1

您是否嘗試過谷歌搜索, 「如何在Python進口」? – NonCreature0714

+0

如果這是python 2,根據它的語法來判斷,你可能需要在同一個目錄中有一個名爲'__init__.py'的文件(無法獲得下劃線語法....) – user3684792

+0

[Python導入力學](http://stackoverflow.com/questions/1917958/python-import-mechanics) – Prune

回答

0

保持文件在同一目錄然後使用類似下面的格式。

from one import One 

one = One() 

class Two: 
    a = 5 
    one.printNumber(a) 

編輯:在Pycharm中工作時,您需要標記您的源根目錄以導入您自己的文件。

enter image description here

+0

也使用從同樣的錯誤。這兩個文件都在同一個目錄中。我正在使用pycharm IDE – Sumith

+0

已將我的答案更新爲與Pycharm一起使用。 –

+0

謝謝,幫助 – Sumith