我最近开始学习使用Python编程,在一些来源中,我遇到了代码:def f(x : int) -> str:或def f(x):
"""(int) -> str...."""当我尝试第一个代码时,它似乎没有限制函数的输入或输出。这是否意味着它们是为了代码清晰,并且它们中的任何一个的使用取决于个人喜好,还是我错过了什么?
1 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
这是否意味着它们是为了代码清晰
是的,键入提示代码通常更易于阅读和理解。
您还可以使用第三方工具来检查您的代码。您可以使用两种工具:mypy和pye。
如果您有一个名为 的模块:example.py
def foo(bar: int) -> str:
return str(bar)
foo("hello, world")
foo(1)
foo(b'\x00')
你可以像这样检查它:
$ mypy example.py
example.py:5: error: Argument 1 to "foo" has incompatible type "str"; expected "int"
example.py:7: error: Argument 1 to "foo" has incompatible type "bytes"; expected "int"
Found 2 errors in 1 file (checked 1 source file)
添加回答
举报
0/150
提交
取消
