eep*_*epp 5 python python-3.x type-annotation python-typing
假设我定义了一个新类型:
import typing
Index = typing.NewType('Index', int)
Run Code Online (Sandbox Code Playgroud)
然后假设我有一个Index变量:
index = Index(0)
Run Code Online (Sandbox Code Playgroud)
增量的惯用方法是index什么?
如果我做
index += 1
Run Code Online (Sandbox Code Playgroud)
这相当于
index = index + 1
Run Code Online (Sandbox Code Playgroud)
那么类型index变为int而不是Index从静态类型检查的角度来看:
$ mypy example.py
Run Code Online (Sandbox Code Playgroud)
example.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "Index")
Run Code Online (Sandbox Code Playgroud)
有什么比
index = Index(index + 1)
Run Code Online (Sandbox Code Playgroud)
保持Index类型?
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |