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.htmlPyVideo, Gradual Typing for Python 3
PEP 484 – Type Hints
相关文章推荐
- Python 3.5 终于将 Type Hint(类型提示)官方化
- Python 3.5 终于将 Type Hint(类型提示)官方化
- 函数类型提示(Callable typehint)
- 函数类型提示(Callable typehint)
- python判断变量类型时,为什么不推荐使用type()方法
- 教你用Type Hint提高Python程序开发效率
- 《Python 源码阅读》之 类型Type
- Python对<type 'NoneType'>数据类型的处理
- python数据类型判断type与isinstance的区别
- python机器学习实战3.2提示错误AttributeError: type object 'str' has no attribute '_name_'
- Python的type 还是要靠isinstance判断类型
- 编辑控件的警告提示是:This text field does not specify an inputType or a hint
- 《Python 源码阅读》之 类型Type
- python 判断参数为Nonetype类型或空
- python数据类型判断type与isinstance的区别
- type error:this constructor takes no arguments的错误提示(python)
- skyeye-1.3.5运行提示python: undefined symbol: PyFloat_Type 和 undefined symbol: PyUnicodeUCS2_FromUnicode
- Python类型判断type与isinstance
- Python isinstance 和 type,类型判断
- PHP Type Hinting (类型提示)