编辑:我应该指定我正在(卡住)使用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
,但是这样的事情可能吗?你知道吗
您可以通过在初始化时自动在
shapes
命名空间中构造所有可能的对象来实现这一点,只要可能的类不太多,并且预先初始化类的成本不太高。你应该用这样的代码形状.py地址:相关问题 更多 >
编程相关推荐