如何解决如何在基类中实现一个函数,该函数返回python子类中的泛型类型?
背景:我使用泛型将配置类绑定到它们各自的类。我正在使用一个小工厂,它从 json 文件创建配置对象,然后使用这些配置对象来初始化实际的类。对于每个类,我需要一个类方法,它为我提供了预期的配置类的类型,以便我可以将预期的配置对象传递给构造函数。我想练习 DRY,因此我不想在子类的主体中重复配置类型,因为它已经在类签名中定义。所以我想要一个基类中的方法,它只返回特定子类的预期配置类型。我当前的解决方案使用一个大的“if-elif”块,它明确地将每个类映射到它们的配置类。
如何在基类中实现返回子类中泛型类型的函数?
或者换一种说法:如何在基类型的函数中获得泛型的特定类型?
我使用的是 python3.8,但也欢迎更新版本的解决方案。
代码示例:我需要如何修改本示例中的 Base 类,以便最终将截取的内容打印为 true? (而且 mypy 也没有报告错误)
import abc
from typing import TypeVar,Generic,Type,get_args
from torch.nn import Module
class BaseCfg:
pass
CfgClass = TypeVar("CfgClass",bound=BaseCfg)
class Base(abc.ABC,Generic[CfgClass]):
def __init__(self,config: CfgClass):
self.config: CfgClass = config
@classmethod
def get_config_type(cls) -> Type[BaseCfg]:
# this method and it's signature probably need to change
return BaseCfg
class Child1Cfg(abc.ABC,BaseCfg):
pass
class Child1(Base[Child1Cfg]):
pass
class Child2Cfg(abc.ABC,BaseCfg):
pass
CfgClass2 = TypeVar("CfgClass2",bound=Child2Cfg)
class Child2(Base[CfgClass2]):
pass
class Child2aCfg(Child2Cfg):
pass
class Child2a(Child2[Child2aCfg]):
pass
class Child2bCfg(Child2Cfg):
pass
class Child2b(Module,Child2[Child2bCfg]):
pass
print(Child1.get_config_type() == Child1Cfg)
print(Child2a.get_config_type() == Child2aCfg)
print(Child2a.get_config_type() == Child2bCfg)
print(Child1.get_config_type())
print(Child2a.get_config_type())
print(Child2a.get_config_type())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。