拦截模块调用? [英] Intercepting module calls?

查看:80
本文介绍了拦截模块调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拦截"对特定模块的所有调用,然后将它们重新路由到另一个对象.我想这样做,以便可以拥有一个相当简单的插件体系结构.

I'm trying to 'intercept' all calls to a specific module, and reroute them to another object. I'd like to do this so that I can have a fairly simple plugin architecture.

例如,在main.py

For example, in main.py

import renderer

renderer.draw('circle')

在renderer.py

In renderer.py

specificRenderer = OpenGLRenderer()

#Then, i'd like to route all calls from main.py so that
#specificRenderer.methodName(methodArgs) is called
# i.e. the above example would call specificRenderer.draw('circle')

这意味着任何函数都可以导入渲染器并使用它,而无需担心细节.这也意味着我可以完全改变渲染器,只需创建另一个对象并将其分配给renderer.py中的"specificRenderer"值即可.

This means that any function can just import renderer and use it, without worrying about the details. It also means that I can completely change the renderer just by creating another object and assigning it to the 'specificRenderer' value in renderer.py

有什么想法吗?

推荐答案

renderer.py中:

import sys

if __name__ != "__main__":
    sys.modules[__name__] = OpenGLRenderer()

模块名称现在已映射到OpenGLRenderer实例,其他模块中的import renderer将获得相同的实例.

The module name is now mapped to the OpenGLRenderer instance, and import renderer in other modules will get the same instance.

实际上,您甚至不需要单独的模块.您可以这样做:

Actually, you don't even need the separate module. You can just do:

import sys
sys.modules["renderer"] = OpenGLRenderer()
import renderer   # gives current module access to the "module"

...主模块中的第一件事.再次在其他模块中导入renderer时,将引用同一实例.

... first thing in your main module. Imports of renderer in other modules, once again, will refer to the same instance.

您确定首先确实要执行此操作吗?人们并不是真正希望模块如何表现.

Are you sure you really want to do this in the first place? It isn't really how people expect modules to behave.

这篇关于拦截模块调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆