如何在 python 类型中指示参数应该是对派生 class 的引用?

How to indicate an argument should be a reference to derived class in python typing?

我想将 class 本身作为参数传递给构造函数。我知道在 Python 中是可能的,但我在理解如何编写正确的打字注释时遇到了问题。用例如下:

在 class A 的构造函数中,我想传递对某些 class X 的引用(不是 class [=14 的对象=]) 在 BaseX 之后继承。 XBaseX 都来自图书馆。除了对 X 的引用之外,A 的构造函数接受有助于构建 X:

的参数
# Library
class BaseX:
    def func():
        print("Hey BaseX")

class X(BaseX):
    def func():
        print("X!")

# My client code
class A:
    def __init__(arg x, arg y, layer: BaseX): # what should be the annotation of layer?
        # construct BaseX object
        self.layer = BaseX(x=x, y=y) # IDEs show x and y as  unexpected arguments because they treat BaseX as an object and look into its __call__ func

A(5, 6, X)

我不确定如何表达图层的注释,以便它可以被视为 class 并确保它是 BaseX 的导数。我还想问一些关于这是否是 Pythonic 方法来做到这一点的评论。

干杯!

您可以使用注释 Type[BaseX] 指示变量是对类型的引用(请参阅 Python docs on Type)。用 Type[T] 注释的变量包含 T.

的子类型的任何类型

对于“构造指定类型的对象,它是BaseX的子类型”的特定用例,您可以借助TypeVar使用更准确的注释。例如:

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

def construct(cls: Type[T], *args, **kwargs) -> T:
    return cls(*args, **kwargs)

这里:

  • TypeVar('T', bound=BaseX) 定义了一个“类型变量”,它可以被 BaseX“限定”的任何类型替代,即,是 BaseX.
  • 的子类型
  • construct 函数接受一个带有注释 Type[T] 的参数 cls,表明它是对 BaseX.
  • 子类型的引用
  • return类型注解是T,表示returned值是BaseX.
  • 子类型的一个实例
  • 函数中出现的所有类型变量或 class 都绑定到同一类型。在这种情况下,returned 值的类型是作为参数传递的类型。