2015-01-02 20 views
0

我道歉了一個看似簡單的問題,我是新來使用Python中的類。在當前的代碼中使用從另一個文件夾類

我使用Pycharm,我的文件夾結構如下所示:

enter image description here

文件夾constant-contact-python-wrapper__init.py__restful_lib.py下定義的幾類(我得到這個庫從github)。我想在包含在ConstantContact文件夾中的文件Trial.py中使用這些類。我正在使用下面的代碼,但它無法導入類。

import sys 
sys.path.append('C:\\Users\\psinghal\\PycharmProjects\\ConstantContact\\constant-contact-python-wrapper') 
import constant-contact-python-wrapper 

API_KEY = "KEY" #not a valid key 
mConnection = CTCTConnection(API_KEY, "joe", "password123") 

有人能請我指出正確的方向嗎?

回答

1

部分是,你有兩個庫是在同一個範圍內,即使它不看,他們一定需要。

最簡單的解決辦法是簡單的放在ConstantContact文件夾恆定接觸蟒蛇,包裝下的代碼一個新文件夾要導入你自己沒寫。這樣,你的項目爲這個實例和未來的情況下舉辦的,你輸入的代碼是從其他圖書館

理想情況下的文件夾結構將是:

ConstantContact 
|___ ConstantContact 
    |____ExternalLibraries #(or some name similar if you plan on using different libraries) 
     |___constant-contact-python-wrapper 

使用上述模型,你現在有一個有組織的非常容易適應導入的代碼。


爲方便導入你會還設置如下:

1.創建初始化在ExternalLibraries .py文件。內容如下:

from constant-contact-python-wrapper import #The class or function you want to use 

這將有助於導入,並且可以爲將來選擇使用的庫進行擴展。

然後可以使用import語句在你的代碼寫在ConstantContact文件夾:

from ExternalLibraries import #The class or function you chose above 

,如果你有多個類,你想導入,您可以用逗號分隔的import語句它們分開。例如:

from Example import foo,bar,baz 

由於ExternalLibraries的初始化 .py文件直接導入所有功能/班,現在就可以使用它們,甚至無需使用點語法(即library.func)。

來源和進一步閱讀:

所有和進口*」 Can someone explain __all__ in Python?

「Python項目骷髏」 http://learnpythonthehardway.org/book/ex46.html

「模塊」 http://docs.python-guide.org/en/latest/writing/structure/#modules

+0

這是一個很好的答案,非常感謝您的詳細信息,非常感謝! – Patthebug

+0

不客氣:) –

1

constant-contact-python-wrapperConstantContact是蟒蛇無關包。在與manage.py相同的目錄中創建__init__.py,它應該按預期工作。你試圖糾正問題的

+0

我這樣做,但是'__init __。py'的內容應該是什麼文件? – Patthebug

+0

@Patthebug它可以是一個空文件 – pad

+0

我試過了,但我的代碼似乎仍然沒有工作。 – Patthebug

相關問題