Python:动态创建对象,因为它们';再进口?
我想编写一个python包,它将在您尝试导入可导入对象时动态创建这些对象 如果你写信的话Python:动态创建对象,因为它们';再进口?,python,python-import,python-module,Python,Python Import,Python Module,我想编写一个python包,它将在您尝试导入可导入对象时动态创建这些对象 如果你写信的话 from importTest import importable 当您键入时,它将正确定义导入的importable 我想也许我可以通过覆盖模块上的\uuuu getattribute\uuuu来实现这一点,如下所示,但这不起作用: import sys def getService(self, name): # Ultimately, I want this to query a web s
from importTest import importable
当您键入时,它将正确定义导入的importable
我想也许我可以通过覆盖模块上的\uuuu getattribute\uuuu
来实现这一点,如下所示,但这不起作用:
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!'
是否需要导入每个服务?为什么不使用
getService
函数来创建服务(并缓存它们)?@ColonelThirtyTwo-显然我不需要这样做。我也不需要使用字典文本。我可以只做一本空字典,然后反复添加。同样的结果。只是杂乱无章。类似地,我更希望最终用户编写的代码能够像通常一样导入类,而不必了解底层细节,并使用此函数返回动态生成的类。我相信我可以通过让最终用户更改\uuuuuu import\uuuuu
函数来完成这类工作,但这也会很难看。因此,你是说你想创建一个模块,它没有定义类似importable
,但是你尝试导入它,它神奇地出现了?@BryanOakley-没错。这些服务都存在于服务器上。它们日复一日地来来去去去——我不想不断地更新我的python模块来反映这一点。我更希望模块在用户尝试导入时检查服务器并获得正确的对象。似乎要解决一些工厂函数巧妙解决的问题会有很多麻烦。