【问题标题】:Dynamic typing of subclasses using generics in Python在 Python 中使用泛型对子类进行动态类型化
【发布时间】:2021-04-03 02:51:06
【问题描述】:

假设我必须上课。

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

【问题讨论】:

    标签: python generics inheritance subclass python-typing


    【解决方案1】:

    You can supply a bound:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2021-09-21
      • 2019-07-26
      • 2017-12-23
      • 2019-01-03
      • 1970-01-01
      相关资源
      最近更新 更多