更改 python 类型提示的成员参数类型
Change type of member parameter for python type hint
我有这样的代码:
class A:
def __init__(self, a: int) -> None:
self.a: int = a
class B(A):
def __init__(self, a: float) -> None:
self.a: float = a
问题是 self.a 从基数 class、A 中的类型 int 更改为 float 在 class B.mypy 中给我这个错误:
typehintancestor.py:8: error: Incompatible types in assignment (expression has type "float", variable has type "int")
(第8行是最后一行)
这是 mypy 中的错误还是我应该更改 class B 的实现?
这是您的代码中的错误。假设以这种方式定义 类 是合法的,我们编写了以下程序:
from typing import List
# class definitions here
def extract_int(items: List[A]) -> List[int]:
return [item.a for item in items]
my_list: List[A] = [A(1), A(2), B(3.14)]
list_of_ints = extract_int(my_list)
我们希望 list_of_ints
变量只包含一个整数,但它实际上包含一个浮点数。
基本上,mypy 强制您的代码遵循此处的 Liskov substitution principle。
我有这样的代码:
class A:
def __init__(self, a: int) -> None:
self.a: int = a
class B(A):
def __init__(self, a: float) -> None:
self.a: float = a
问题是 self.a 从基数 class、A 中的类型 int 更改为 float 在 class B.mypy 中给我这个错误:
typehintancestor.py:8: error: Incompatible types in assignment (expression has type "float", variable has type "int")
(第8行是最后一行)
这是 mypy 中的错误还是我应该更改 class B 的实现?
这是您的代码中的错误。假设以这种方式定义 类 是合法的,我们编写了以下程序:
from typing import List
# class definitions here
def extract_int(items: List[A]) -> List[int]:
return [item.a for item in items]
my_list: List[A] = [A(1), A(2), B(3.14)]
list_of_ints = extract_int(my_list)
我们希望 list_of_ints
变量只包含一个整数,但它实际上包含一个浮点数。
基本上,mypy 强制您的代码遵循此处的 Liskov substitution principle。