使用 python 2 类型注释指定实例变量的类型
Specify type of instance variables using python 2 type comments
我正在尝试使用 PEP 484 的 python 2 syntax 指定实例变量的类型。但是我还没找到什么方法可以在python2中不初始化变量就添加类型,相当于下面的python3:
value: int
我通常的解决方法是在实例化变量时在 __init__
中声明变量的类型。但是,这不适用于实例变量的类型应该是协议一部分的协议(__init__
中的类型似乎不算数)。这是 Python 3 中我使用默认实现的示例:
from typing_extensions import Protocol
class A(Protocol):
value: int
def get_value(self) -> int:
return self.value
如果 value
未正确初始化,这将突出显示错误:
class B(A):
pass
B() # error: Cannot instantiate abstract class 'B' with abstract attribute 'value'
然而,将其转换为python 2 类型的注释无法通过mypy。无论有没有 __init__
声明,它都会给出相同的错误。
class A(Protocol):
def __init__(self):
# type: () -> None
self.value = 0 # type: int
def get_value(self):
# type: () -> int
return self.value # error: "A" has no attribute "value"
在 python 2 中是否有一些特殊的语法来声明变量类型而不初始化它们?
Mypy 的协议使用class 变量 来定义属性。否则 mypy 不会在 class 与实例变量之间做出特别精细的区分。把这两件事结合起来,你可以写出如下代码:
from typing_extensions import Protocol
class A(Protocol):
value = None # type: int
def get_value(self):
# type: () -> int
return self.value
# below here it's just to validate that the protocol works
class B(object):
def __init__(self, value):
# type: (int) -> None
self.value = value
def get_value(self):
# type: () -> int
return self.value
a = B(42) # type: A
我正在尝试使用 PEP 484 的 python 2 syntax 指定实例变量的类型。但是我还没找到什么方法可以在python2中不初始化变量就添加类型,相当于下面的python3:
value: int
我通常的解决方法是在实例化变量时在 __init__
中声明变量的类型。但是,这不适用于实例变量的类型应该是协议一部分的协议(__init__
中的类型似乎不算数)。这是 Python 3 中我使用默认实现的示例:
from typing_extensions import Protocol
class A(Protocol):
value: int
def get_value(self) -> int:
return self.value
如果 value
未正确初始化,这将突出显示错误:
class B(A):
pass
B() # error: Cannot instantiate abstract class 'B' with abstract attribute 'value'
然而,将其转换为python 2 类型的注释无法通过mypy。无论有没有 __init__
声明,它都会给出相同的错误。
class A(Protocol):
def __init__(self):
# type: () -> None
self.value = 0 # type: int
def get_value(self):
# type: () -> int
return self.value # error: "A" has no attribute "value"
在 python 2 中是否有一些特殊的语法来声明变量类型而不初始化它们?
Mypy 的协议使用class 变量 来定义属性。否则 mypy 不会在 class 与实例变量之间做出特别精细的区分。把这两件事结合起来,你可以写出如下代码:
from typing_extensions import Protocol
class A(Protocol):
value = None # type: int
def get_value(self):
# type: () -> int
return self.value
# below here it's just to validate that the protocol works
class B(object):
def __init__(self, value):
# type: (int) -> None
self.value = value
def get_value(self):
# type: () -> int
return self.value
a = B(42) # type: A