Mypy 在传递具有子类类型的参数时抛出“具有不兼容的类型”错误

问题描述 投票:0回答:1

我使用 python 的

typing
模块创建了一个泛型类型

TDbBase = TypeVar('TDbBase', bound=MyBaseClass)

我还定义了两个类,它们是子类

MyBaseClass

class MyFirstClass(MyBaseClass):
class MySecondClass(MyBaseClass):

我有一个方法需要采用

MyFirstClass
MySecondClass
的对象,因此我将方法签名编写为

def foo(self, mytype: TDbBase) -> None:

但是当我尝试使用该方法并传递

MyFirstClass
类型的对象或
MySecondClass
类型的对象时,我从
mypy

收到此错误
Argument 1 to "foo" of "some_module.py" has incompatible type "MyFirstClass"; expected "TDbBase" 

我也尝试过像这样编写方法签名,在阅读 PEP-484 中的示例后

def foo(self, mytype: Type[TDbBase]) -> None:

但是我遇到了同样的错误,

error: Argument 1 to "foo" of "some_module.py" has incompatible type "MyFirstClass"; expected "Type[TDbBase]"
python mypy python-typing
1个回答
0
投票

我没有看到任何错误:

class MyBaseClass: ...
class MyFirstClass(MyBaseClass): ...
class MySecondClass(MyBaseClass): ...
TDbBase = TypeVar('TDbBase', bound=MyBaseClass)
def foo(mytype: TDbBase) -> None: ...
x = MyFirstClass()
foo(x)
y = MySecondClass()
foo(y)

参见:https://mypy-play.net/?mypy=latest&python=3.10&gist=ded683650c84bd98e713522b61cb816c

© www.soinside.com 2019 - 2024. All rights reserved.