2009-06-11 46 views
0

我想進口/定位到一個名爲蟒蛇遞歸類夾雜物及實例

一些-dir的文件夾 類

,並命名爲類*的.py

最後實例化它們。

這是最好的方式來看看文件夾內,導入類 並實例化它們?

+2

你有什麼嘗試?你讀過關於進口陳述嗎?由於這是導入的內容,我無法理解你的問題。 – 2009-06-11 16:22:39

+0

Giorgio的回答非常有用 – DrFalk3n 2009-06-12 07:45:27

回答

-1

嘗試:

import os 
#get files 
files = os.listdir("some-dir/") 
classes = [] 
for f in files: 
    #find python modules in file listing 
    if(f.find(".py") != -1): 
     #remove file extenstion 
     f = f.rstrip(".py") 
     #create string to add module to global namespace, import it and instantiate 
     #class 
     importStr = "global " + f +";import " + f + "; classes.append(" + f +"())" 
     #execute the code 
     exec(importStr) 

這是一個首次嘗試它。這假定你沒有任何參數傳遞給類實例化。

不知道它是否有效,但它可以開始。 「exec」語句可讓您以python代碼的形式執行字符串。

希望這可以幫助你在正確的方向。