列出多态继承选择并根据该选择创建一个实例

List polymorphic inheritance choices and create an instance based on that choice

我有一个连接表继承,例如 Animal、Cat 和 Dog。我想让用户创建一个新的动物。

有没有办法把所有的类型(猫,狗)放到一个列表中供用户使用?有没有办法让用户选择并从中创建一个实例? (我不想硬编码 if choice == "cat": Cat()。)

SQLAlchemy 跟踪父模型的多态子模型。使用 inspect on the Animal model to find a mapping of polymorphic identities.

>>> from sqlalchemy import inspect
>>> i = inspect(Animal)
>>> i.polymorphic_map
{'cat': <Mapper at 0x7fb4c7a8b390; Cat>,
 'dog': <Mapper at 0x7fb4c7a98240; Dog>}

您可以使用 class_ 属性从映射器中获取 class。

>>> i.polymorphic_map['cat'].class_
__main__.Cat

有了这两个部分,您现在可以获得要呈现给用户的类型列表,并且您可以根据所选值实例化模型。

types = inspect(Animal).polymorphic_map.keys()
user_input = 'cat'
new_cat = inspect(Animal).polymorphic_map[user_input]()

如果层级有更多级别,例如 CalicoCatHairlessCat,您可以使用 polymorphic_iterator 查看整个层级。