Python 中可以重载 from/import 吗?
Python 中是否可以重载 from/import 语句?
例如,假设jvm_object
是类JVM
的实例,是否可以编写以下代码:
class JVM(object):
def import_func(self, cls):
return something...
jvm = JVM()
# would invoke JVM.import_func
from jvm import Foo
Is it possible to overload the from/import statement in Python?
For example, assuming jvm_object
is an instance of class JVM
, is it possible to write this code:
class JVM(object):
def import_func(self, cls):
return something...
jvm = JVM()
# would invoke JVM.import_func
from jvm import Foo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这篇文章演示了如何使用介绍的功能在 PEP-302 中通过网络导入模块。我将其发布为如何自定义导入语句的示例,而不是建议的用法;)
This post demonstrates how to use functionality introduced in PEP-302 to import modules over the web. I post it as an example of how to customize the import statement rather than as suggested usage ;)
很难找到像 Python 这样的动态语言中不可能实现的东西,但我们真的需要滥用一切吗?不管怎样,它是这样的:
但是我在几个库/项目中看到的一种模式是某种
_make_module()
函数,它动态创建ModuleType
并初始化所有内容在其中。之后,当前模块将被新模块替换(使用对sys.modules
的赋值),并且_make_module()
函数将被删除。这样做的优点是,您可以循环模块,甚至可以在循环内向模块添加对象,这有时非常有用(但请谨慎使用!)。It's hard to find something which isn't possible in a dynamic language like Python, but do we really need to abuse everything? Anyway, here it is:
But one pattern I've seen in several libraries/projects is some kind of a
_make_module()
function, which creates aModuleType
dynamically and initializes everything in it. After that, the current Module is replaced by the new module (using the assignment tosys.modules
) and the_make_module()
function gets deleted. The advantage of that, is that you can loop over the module and even add objects to the module inside that loop, which is quite useful sometimes (but use it with caution!).