1.typing hint的使用
1.为什么我们需要指定变量类型?
在最开始接触python时,我是比较喜欢不需要指定变量类型这一特性的,代码也是怎么快速,怎么随意,怎么来。当然,结果就是编程5分钟,debug半小时。 不过,当时也乐在其中,傻呼呼的。
直到有一次,在对一个比较大的项目进行修改时,各种变量名让人眼花缭乱,不知所谓。本来很小的改动,也是频繁报错,需要缝缝补补很长时间。这时才真正体会到了指定变量类型的意义。
- 使用typing编辑器能给更多的提示,如下面的类型注解可以看到
- 后期的修改维护,以及协同开发更加便利
- 在比较好的开源项目都使用到了typing hint,理解后可以帮助更好的阅读开源代码
2. 基本使用
参考:官方文档:typing
下面代码实例在python 3.8正常运行
本文只做一些基本常用的介绍,给大家提供一个思路,有个全局的概览。网上有很多其它文章写的很深入详细,我就不多
1. 基本类型
def moon_weight(earth_weight: float) -> str:
return f'On the moon, you would weigh {earth_weight * 0.166} kilograms.'
2. 列表类型
def scale(scalar: float, vector: List[float]) -> List[float]:
return [scalar * num for num in vector]
# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
3. 函数类型
from typing import Callable
def int_to_str(i: int) -> str:
return str(i)
def f(fn: Callable[[int], str], i: int) -> str:
return fn(i)
f(int_to_str, 2)
4. 对象类型
对象类型我觉得是比较有趣的,如果使用注解ide会提示该对象的方法,这给开发提供极大便利。
class hello:
def __init__(self) -> None:
pass
def hi(self):
print('hi')
print('测试class注解')
def test(my_class:hello):
my_class.hi()
a = hello()
test(a)
可以看到使用对象类型也比较简单,直接将指定对象名放在参数后面
2.给类型设置别名
使用Vector作为List[float]的别名
from typing import List
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
使用assert
按需使用assert,可以提高代码的健壮性。