Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用mypy的泛型self和python2类型的注释_Python_Python 2.7_Types_Mypy_Typehints - Fatal编程技术网

使用mypy的泛型self和python2类型的注释

使用mypy的泛型self和python2类型的注释,python,python-2.7,types,mypy,typehints,Python,Python 2.7,Types,Mypy,Typehints,我有一个案例,我想使用一个用于使用mypy键入的。但是,我需要保持python 2.7的兼容性,所以我使用类型注释语法 from typing import TypeVar T = TypeVar('T', bound='Shape') class Shape: def set_scale(self: T, scale: float) -> T: self.scale = scale return self 如何将此代码转换为类型注释?类型注释

我有一个案例,我想使用一个用于使用mypy键入的。但是,我需要保持python 2.7的兼容性,所以我使用类型注释语法

from typing import TypeVar

T = TypeVar('T', bound='Shape')

class Shape:
    def set_scale(self: T, scale: float) -> T:
        self.scale = scale
        return self
如何将此代码转换为类型注释?类型注释省略了“self”类型,因此T定义丢失:

    def set_scale(self, scale):
        # type: (float) -> T
你不必排斥自己;您可以选择这样做:

当使用缩写形式时,例如type:str,int->None,必须考虑每个参数,实例和类方法的第一个参数除外,它们通常被忽略,但允许包含它们

从PEP-484开始,第三个音符在

这样你就可以写作了

def set_scale(self, scale):
    # type: (T, float) -> T

此类评论的使用者的工作是计算参数,并确定是否省略了self。

完美!我本该想试试的。