python - 在 Python 中使用泛型动态键入子类

标签 python generics inheritance subclass python-typing

假设我必须上课。

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 .有没有办法将泛型指定为某种类型?

最佳答案

You can supply a bound :

T = TypeVar('T', bound=A)

关于python - 在 Python 中使用泛型动态键入子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65441933/

相关文章:

python - 堆叠相同数组列表时 numpy vstack/c_ 的奇怪行为

python - Pycharm 没有显示结果

python - 使用 python 提取 tarfile 列表

c# - C# 中的通用阶乘函数

python - 访问列表元素并调用它们的函数

generics - 概括 haskell 中的 Maybe 和 Either 函数

python - 当 git commit-msg Hook 失败时,如何恢复提交消息?

c++ - 空基类构建开销?

java - "super"在继承方法中引用哪个类?

java - Java是否支持多重继承?