2016-12-06 97 views
1

我有具有功能hello()是否可以將模塊注入導入模塊的全局變量?

hello.py文件hello.py

def hello(): 
    print "hello world" 

我還有一個文件test.py其中進口hello,並調用函數。

test.py

from hello import * 

def run(): 
    hello() 

if __name__ == '__main__': 
    run() 

如果我運行test.py通過蟒蛇,它按預期工作:

$ python test.py 
hello world 

但是現在,我編輯test.py,並除去import語句

test.py

def run(): 
    hello() # hello is obviously not in scope here 

if __name__ == '__main__': 
    run() 

我介紹一個第三文件,run.py,這進口都hello.pytest.py

run.py

from hello import * 
from test import * 

if __name__ == '__main__': 
    run() 

自然這不起作用,因爲hello()不在test.py's範圍內。

$ python run.py 
Traceback (most recent call last): 
    File "run.py", line 5, in <module> 
    run() 
    File "test.py", line 4, in run 
    hello() 
NameError: global name 'hello' is not defined 

問:

  • 是否有可能注入hello()成從run.pytest.py's範圍,而無需run.py進口hello.py

我很高興使用低級功能,如imp模塊,如果這是必需的。

+3

這是可能的,但隱藏你的依賴從來就不是一個好主意。 – wim

+0

@wim現在離開這是個好主意還是不行,如果可能的話,請分享一下。 –

+0

@wim關於爲什麼我在尋找這個上下文,請參見[這個問題](http://stackoverflow.com/questions/41004393/boostpython-expose-ac-class-to-a-python-script-embedded -in-ac-app) –

回答

2

是的。一個模塊的屬性是其全局變量,所以你可以在那裏戳它。

import test 
import hello 
test.hello = hello.hello 

我會重申wim的評論,這通常不是一個好主意。

+0

男人,就這麼簡單!謝謝!我完全理解這不是一個好主意,所以也許如果你可以看看[這個問題](http://stackoverflow.com/questions/41004393/boostpython-expose-ac-class-to-a-python-script-嵌入式應用程序),並提供一個優秀的解決方案,我真的很感激它 –

1

模塊是可變的:

import hello 
import test 

test.hello = hello.hello 

if __name__ == '__main__': 
    test.run() 
0

你所描述可疑像類的聲音。如果它像一個班級一樣走路,它像一個班級一樣講話,這是一個班級。

hello.py

class Hello(object): 
    @classmethod 
    def hello(class_): 
     print("Hello, world!") 

test.py

class Test(object): 
    @classmethod 
    def run(class_): 
     class_.hello() 

run.py

import hello 
import test 

class Run(hello.Hello, test.Test): 
    pass 

if __name__ == '__main__': 
    # Note: we don't instantiate the class. 
    Run.run() 

這不會給你完全一樣的語法,所以它不直接回答你的問題,但它給你一樣的你正在尋找的功能,而不訴諸意想不到的黑客,如修改其他模塊。

我所描述的不是只有方法來解決這個問題,但有一個模塊修改另一個模塊可以是一個相當令人驚訝的方式爲您的代碼工作。