您的位置:首页 > 编程语言 > Python开发

python TypeHint, 类型提示

2017-09-08 09:40 701 查看

1.简介

def fun(x):
x.???    #can't hint or check


写函数的时候, 编译器并不知道形参x的类型, 所以你调用x的字段与方法的时候, IDE 既不能提示也不能检查, 让人很捉急.

这是动态语言的通病. 所以很多人更喜欢java, c++.

但各种语言都是与时俱进的, javascript 有了 超集 TypeScript. 那么 python3 也在语言级别加入了 type hint. Provide a standard way of annotating a function’s parameters and return values.

python 仍是一门 动态语言, 所以这个注解加不加都可以.

2.语法

2.1 函数参数及返回类型

# 指定参数的类型, 函数的返回类型, 以及局部变量的类型
def foo(a: str, b: str) -> str:
c = None  # type:str
return 'hi'


2.2 普通变量

# 指定参数的类型, 函数的返回类型, 以及局部变量的类型
x = None # type: str
x= '' # 其实IDE已经能知道是str类型了


2.3 类的成员字段

class Student:
def __init__(self):
self.name=None # type: str




2.4 集合泛型

my_list=[] # type: list[Student]
my_map={} # type: dict[int,str]
my_list_2=None # type: Tuple[int,Tuple[int]]




from typing import List,Tuple,Set

需要注意, 注释后面, 写
list
,
List
都可以, 但不在注释后面的typeHint, 如形参及返回类型, 必须使用typing 包下相应的类.



figure 形参后面必须用typing包下的类

3. TypeHint in PyCharm



图 3-1 Specifying types of parameters



图 3-2 Specifying return types



图3-3 specify the types of local variables and attributes

4. hint vs. check

As the name says, type hints are just hints, 所以只做提示不做检查.

但 IDE 可以做检查, 避免出错.



pic 4-1 Inspections in PyCharm

参考

type-hinting-in-pycharm.html

PyVideo, Gradual Typing for Python 3

PEP 484 – Type Hints
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python