2016-12-06 170 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() 

这不会给你完全一样的语法,所以它不直接回答你的问题,但它给你一样的你正在寻找的功能,而不诉诸意想不到的黑客,如修改其他模块。

我所描述的不是只有方法来解决这个问题,但有一个模块修改另一个模块可以是一个相当令人惊讶的方式为您的代码工作。