Python中的magic导入

2024-10-01 11:40:57 发布

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

编辑:我应该指定我正在(卡住)使用python2,但是我想看看如何在2或3中解决这个问题

场景: 我有一个名为shapes的包。你知道吗

我在shapes中有一个名为factory的模块,它有一个ShapeClassFactory类。 该类可以被传递一个字符串,它将在远程数据库中查找数据,并使用该数据动态定义一个类,然后返回该类。你知道吗

你知道吗形状.py地址:

from .factory import ShapeClassFactory
__all__ = ['ShapeClassFactory']

实际上,此软件包可用于各种其他软件包和脚本中,例如:

from shapes import ShapeClassFactory

Circle = ShapeClassFactory("Circle")
Rect = ShapeClassFactory("Rect")

myCircle = Circle(r=5, fill='red')
mySquare = Rect(x=5, y=5, fill=None)

问题: 以上都可以。但是,我希望能够以这样一种方式编写shapes包,它可以这样使用:

from shapes import Circle, Rect

myCircle = Circle(r=5, fill='red')
mySquare = Rect(x=5, y=5, fill=None)

…其思想是,如果在shapes中找不到成员,它将使用ShapeClassFactory来尝试生成它。你知道吗

困难在于,在请求之前,基本上不知道可用的类,因此预定义的类名列表没有帮助。你知道吗

如果ShapeClassFactory无法构建类,我不介意抛出一个ImportError,但是这样的事情可能吗?你知道吗


Tags: 数据fromrectimportnone编辑factoryred
1条回答
网友
1楼 · 发布于 2024-10-01 11:40:57

您可以通过在初始化时自动在shapes命名空间中构造所有可能的对象来实现这一点,只要可能的类不太多,并且预先初始化类的成本不太高。你应该用这样的代码形状.py地址:

from .factory import ShapeClassFactory

__all__ = ['ShapeClassFactory']

def get_shape_names():
    """Returns all valid shapes that can be passed in to ShapeClassFactory"""
    return ['Circle', 'Rect']  # your own code should query the database

for name in get_shape_names():
    globals()[name] = ShapeClassFactory(name)
    __all__.append(name)

相关问题 更多 >