Python:在导入对象时动态创建对象?

2024-09-27 23:21:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个python包,它将在您尝试导入对象时动态地创建可导入对象

如果你写信

from importTest import importable

当您键入时,它会正确地定义importable

我想也许我可以通过覆盖模块上的__getattribute__来实现这一点,如下所示,但这不起作用:

import sys

def getService(self, name):
    # Ultimately, I want this to query a web service and create objects
    # as you attempt to import them. Defining them all in advance
    # would make for far too heavy a download, as there are hundreds of
    # thousands defined, and users typically use 2-3.

    # For now, just to test if this dynamic import idea works,
    # just return the string with the name.

    return name + '!'

sys.modules[__name__].__getattribute__ = getService

在你嘲笑和怀疑为什么我会认为这可能会起作用之前,这确实起作用,只是,它不够动态。。。我需要它在真正知道用户试图导入的内容的名称之前不定义属性

import sys
sys.modules[__name__].importable = 'importable!'

Tags: andto对象nameimportreturn定义as

热门问题