2015-08-19 124 views
1

如果我有一個文件,我們會打電話給他test1.py包含:蟒蛇EVAL在「庫」文件

code=''' 
class Something(object): 
    def __init__(self): 
    print "blah blah blah, this is a horrible idea" 
def run(): 
    print "don't preach at me you pretentious fool" 
''' 
eval(compile(code, '<string>', 'exec')) 

然後下面我eval聲明,在同test1的。 PY文件我當然可以做的東西一樣:

x = Something() 
run() 

但是......如果說我有叫test2.py另一個文件,我希望能夠運行run()或在發射import test1後從那裏實例化Something?我假設有必要對locals()globals()進行某些操作,但Google在這裏使我失敗。

+1

不要太難過;標準庫中的collections.namedtuple使用'exec'來執行由文本模板構建的類定義。 – chepner

回答

2

不,我不認爲你需要做的任何一種locals()globals()操縱的,你可以這樣做 - import test1,然後實例Something對象 -

import test1 
x = test1.Something() 
test1.run() 

示例/演示 -

a.py有你test1.py粘貼完全相同的代碼,然後我可以做 -

>>> import a 
>>> x = a.Something() 
blah blah blah, this is a horrible idea 
>>> a.run() 
don't preach at me you pretentious fool 

另外,你應該聽什麼__init__()說,這真是一個可怕的想法。

+0

啊..非常感謝!你應該聽聽run()說什麼。 ;-) – slumtrimpet

+0

PS ......只是爲了後人的緣故,我實際上並沒有在野外使用它。這確實是一個可怕的想法。 – slumtrimpet