python中的未知语句 [重复]

问题描述 投票:0回答:1

一个错别字透露了一个我不明白的说法。谁能解释一下在这种情况下冒号的作用是什么?

>>> test : 'what does this do?'

我想它可能是一个隐式的dict,就像隐式元组一样

>>> 1,2
(1, 2)

但不返回任何东西。于是我就开始搞,发现了一个错误。

>>> True : 'fs'
  File "<stdin>", line 1
SyntaxError: illegal target for annotation

于是我查了一下那个错误,发现 PEP 526 我也不明白:-)

>>> xx : int
>>> xx = 'sdfs'
>>> xx
'sdfs'

我的意思是它不是类型检查,因为我能够分配一个字符串。谁能帮我理解一下?

python implicit-conversion
1个回答
1
投票

这些都是python类型的提示。

由于python是一种动态类型的语言(不同于Java),所以在运行时不会强制执行。然而,它们可以作为一个额外的文档级别。你的linter(比如pylint)可以使用它们来警告你将一个字符串传递到一个期望是int的函数中。你的IDE也可以使用它们来增强自动完成。

有几个包可以帮助你更好地使用类型提示。

字符串类型提示的目的是为了解决循环依赖的问题。

Parent.py

from .Parent import Parent
class Child(Parent):
  parent: Parent
  pass

Parent.py

# from .Child import Child  # This would cause a circular dependency
class Parent:
  child: 'Child'  # String type hint required as Child cannot be imported
  pass
© www.soinside.com 2019 - 2024. All rights reserved.