繁体   English   中英

Python泛型和子类

[英]Python generics and subclasses

我正在尝试将类型注释添加到现有包中,并且显然我缺少了一些重要的东西。 我有一个抽象超类和子类。 超类应该是通用的,而子类应该是特定类型的。 这是一个简单的示例,如果我看到了,又想看到什么:

from typing import Generic, TypeVar

T = TypeVar("T")

class A(Generic[T]):
    def method(self, arg: T):
        ...

class B(A[int]):
    def method(self, arg):
        reveal_locals()

预期(或至少希望):

GenericTest.py:11: note: Revealed local types are:
GenericTest.py:11: note:     arg: int
GenericTest.py:11: note:     self: Any

得到:

GenericTest.py:11: note: Revealed local types are:
GenericTest.py:11: note:     arg: Any
GenericTest.py:11: note:     self: Any

reveal_locals()打印在调用放置的范围内由mypy推断出的变量的类型。 并且在子类中重新定义方法时,您还将覆盖注释(默认情况下,当未明确给出参数注释时,将使用Any )。

这可能更清楚:

class A(Generic[T]):
    def method(self, arg: T):
        ...

class B(A[int]):
    def method(self, arg):
        pass

B().method('')

上面的代码对mypy来说很好,但是下一个给出了错误:

class C(A[int]):
    pass

C().method('')
error: Argument 1 to "method" of "A" has incompatible type "str"; expected "int"

您需要向子类中的方法添加类型注释。 这样做:

from typing import Generic, TypeVar

T = TypeVar("T")

class A(Generic[T]):
    def method(self, arg: T) -> None:
        ...

class B(A[int]):
    def method(self, arg: int) -> None:
        reveal_locals()

...产生以下结果:

test.py:11: note: Revealed local types are:
test.py:11: note:     arg: builtins.int
test.py:11: note:     self: test.B

如果未使用类型提示注释函数,则mypy会将其视为动态类型,并假定其所有参数均为Any类型。

如果您希望mypy在忘记此类提示时向您发出警告,请使用--disallow-untyped-defs命令行标志 (也可以使用--disallow-incomplete-defs运行mypy以取得良好效果。 或者,使用--strict标志运行mypy,该标志将自动启用上述两个标志(以及更多)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM