假设我必须上课。
class A:
@staticmethod
def foo():
pass
class B(A):
pass
我有某种函数可以根据它的类型构造一个对象并调用一个函数。def create(cls: Type[A]) -> A:
cls.foo()
return cls()
现在我可以对该函数进行以下调用。因为B
继承自 A
都很好。instance_a: A = create(A)
instance_b: B = create(B)
除了后者,类型检查将开始提示,因为 create
根据注释返回 A
的实例.这可以通过
TypeVar
解决如下。from typing import Type, TypeVar
T = TypeVar('T')
def create(cls: Type[T]) -> T:
cls.foo()
return cls()
除了现在打字检查不做它的原始工作保证cls
有一个方法叫 foo
.有没有办法将泛型指定为某种类型?
最佳答案
T = TypeVar('T', bound=A)
关于python - 在 Python 中使用泛型动态键入子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65441933/