python 中的annotations

在读代码的时候,我们有时候会遇到别人的代码中定义函数时有以下的写法:
NB(注意): # 后面的部分表示输出结果。

class Debug:
    def calculateSum(self, size: int) -> int:
        return sum(range(size))


if __name__ == "__main__":
    main = Debug()
    result = main.calculateSum(10)
    print(result)                   # 45

我们可以看到这里的参数size后面有一个冒号,并且紧跟着整型int标识符,在括号外还有一个->箭头
并且也跟着一个整型标识符int,这究竟是什么意思呢?其实这是一种特殊的注释方式,为了让我们在使用装饰器等其他函数的时候事半功倍。箭头后面的int标识符告诉使用者,这个函数的返回值应当是一个整型的,size后面的标识符告诉使用者这个函数的输入参数应该是整型的。并且对于->后面的标识符我们可以使用.__annotations__['return']的方法进行获取,代码如下:

def f(x) -> int:
    return int(x)


if __name__ == "__main__": 
    print(f.__annotations__['return'])  # <class 'int'>

我们可以看到f.__annotations__['return']输出的结果<class 'int'>,返回的正是我们的注释类型,此处的f为所定义函数的名称。
我们再看一个例子:

def calculateSum(x:'annotating x', y: 'annotating y', z: int) -> float: print(x + y + z)


if __name__ == "__main__": 
    calculateSum(5,6,7)                             # 18
    print(calculateSum.__annotations__['return'])   # <class 'float'>

我们可以看到此时我们给予函数中的三个参数对用的注释,x,y均为字符串类型的注释,z为整数类型的注释,最终当我们给予x,y,z均为整数类型的数据时,获取了最后的结果18,由此我们可以看到,对于annotation,实际上是不影响真实的计算结果的,只是一种提示性的作用,因此要避免乱用。
print(calculateSum.__annotations__['return'])的结果也得到了正确的返回值的注释类型。
实际上上述函数定义的代码也等同于,

def calculateSum(x:'annotating x', y: 'annotating y', z: int) -> float: 
	print(x + y + z)

这种写法可能更符合我们的通用写法。

猜你喜欢

转载自blog.csdn.net/u011699626/article/details/108470770