Python 3.6即将发布。PEP 494 -- Python 3.6 Release Schedule提到将在12月底发布,因此我查看了What's New in Python 3.6,发现他们提到了变量注释:
从我所读的内容来看,它们是Python 3.5的类型提示的一部分,What are Type hints in Python 3.5中有描述。PEP 484 introduced standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:
primes: List[int] = [] captain: str # Note: no initial value! class Starship: stats: Dict[str, int] = {}
Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in a special attribute
__annotations__
of a class or module. In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the__annotations__
attribute.
我跟随了`captain: str`和`class Starship`的例子,但对于最后一个例子不确定:`primes: List[int] = []`是如何解释的? 它定义了一个允许整数的空列表吗?
primes: List[int] = []
只是一个空列表,就像primes = []
一样。不同之处在于,你声称primes
应该只包含int
类型的元素,第三方应用程序可能会对你的程序进行类型检查以验证这个声明,但在任何 python 解释器中运行代码时,这与编写primes = []
是一样的,因此执行primes: List[int] = []; primes.append("string")
仍然是有效的。 - Bakuriu