gpt4 book ai didi

python - 动态创建子类的类型注解

转载 作者:行者123 更新时间:2023-12-05 04:47:26 26 4
gpt4 key购买 nike

我想在启动时使用 type() 函数动态创建子类。一切都按预期工作。我知道这不是很好,但我受制于一个框架并且必须这样做。另一种选择是生成源代码...

功能等同于我的代码:

class BaseEntity:
id: str


def make_new_entity(name: str, attrs: dict) -> type:
return type('RuntimeEntity', (BaseEntity,), attrs)


RuntimeEntity: ??? = make_new_entity('RuntimeEntity', {'id': 'entity.RuntimeEntity'})

有没有办法为返回的类型提供一个绑定(bind)?基本上相当于

E = TypeVar('E', bound='BaseEntity')

我还查看了 types 模块。

感谢您的帮助!

最佳答案

typing.Type 允许您指定值应该是实际类型,而不是该类型的实例。

from typing import Type

class BaseEntity:
id: str


def make_new_entity(name: str, attrs: dict) -> Type[BaseEntity]:
return type('RuntimeEntity', (BaseEntity,), attrs)


RuntimeEntity: Type[BaseEntity] = make_new_entity('RuntimeEntity', {'id': 'entity.RuntimeEntity'})

Type[BaseEntity] 类型的值可以是 BaseEntity 本身,或任何继承自 BaseEntity 的类。 (描述这个的术语是协方差。如果Type不变Type[BaseEntity] 将接受BaseEntity 本身。)

关于python - 动态创建子类的类型注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68488034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com