在 Python 中使用泛型对子类进行动态类型化
Dynamic typing of subclasses using generics in Python
假设我必须遵循 类。
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
根据注释 returns 一个 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)
假设我必须遵循 类。
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
根据注释 returns 一个 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)