如何通过泛型类型参数调用泛型类中的类方法?
问题原因
Python的泛型TypeVar仅用于静态类型检查,运行时会被擦除,T本身只是一个TypeVar实例,并非实际绑定的B类对象,因此直接调用T.test()会触发'TypeVar' object has no attribute 'test'错误。同时原代码还存在两个问题:
invoke_test作为实例方法缺少self参数;a: A = A[B]错误地将泛型类型(而非实例)赋值给变量,应该创建实例A[B]()。
解决方案
以下两种方法可实现通过泛型调用类方法:
方法一:利用__orig_class__获取实际类型参数(Python 3.10+)
Python 3.10及以上版本支持通过__orig_class__属性获取实例化时的泛型类型,结合get_args提取实际绑定的类:
from abc import ABC, abstractmethod from typing import Generic, TypeVar, get_args class Base(ABC): @classmethod @abstractmethod def test(cls): print('foo') class B(Base): @classmethod def test(cls): print('bar') T = TypeVar("T", bound=Base) class A(Generic[T]): def invoke_test(self): # 提取泛型绑定的实际类 actual_cls = get_args(self.__orig_class__)[0] actual_cls.test() # 创建泛型实例 a = A[B]() a.invoke_test() # 输出: bar
方法二:显式传入类对象(兼容所有Python版本)
如果需要兼容更低版本Python,可在初始化时直接传入目标类并保存,运行时直接调用:
from abc import ABC, abstractmethod from typing import Generic, TypeVar class Base(ABC): @classmethod @abstractmethod def test(cls): print('foo') class B(Base): @classmethod def test(cls): print('bar') T = TypeVar("T", bound=Base) class A(Generic[T]): def __init__(self, target_cls: type[T]): self.target_cls = target_cls def invoke_test(self): self.target_cls.test() # 传入B类创建实例 a = A(B) a.invoke_test() # 输出: bar
内容的提问来源于stack exchange,提问作者Bin4ry
相关产品推荐
相关产品推荐

