使用Python2类型注释指定实例变量的类型

2024-04-27 02:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用pep484的python 2 syntax为实例变量指定类型。但是,在python 2中,我没有找到任何方法在不初始化变量的情况下添加类型,相当于下面的python 3:

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'

但是,将其转换为python2类型的注释无法传递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"

在Python2中是否有一些特殊的语法用于声明变量类型而不初始化它们?你知道吗


Tags: 实例方法self声明协议类型getreturn
1条回答
网友
1楼 · 发布于 2024-04-27 02:21:35

Mypy的协议使用类变量来定义属性。否则mypy不会在类变量和实例变量之间做出特别细微的区分。结合这两件事,您可以编写如下代码:

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

相关问题 更多 >