简体   繁体   English

用数字提示的 Python 类型

[英]Python type hinting with numbers

I've just come across a strange behaviour with Python's type hinting.我刚刚在 Python 的类型提示中遇到了一个奇怪的行为。

>>> def x(y: int):
    return y
>>> d=x('1')
>>> print(type(d))
<class 'str'>
>>> d
'1'

When I pass a number as string into the function where the argument is cast as int, it still produces string.当我将一个数字作为字符串传递给参数被转换为 int 的函数时,它仍然产生字符串。 I think a key to this unexpected behaviour is that it is not casting, but hinting.我认为这种意外行为的关键在于它不是投射,而是暗示。 But why does it behave like this?但它为什么会这样呢? If I pass 'one' as an argument it gives me a NameError.如果我将“one”作为参数传递,它会给我一个 NameError。

You're not casting anything inside the function and type hints are just that;您没有在函数内部投射任何内容,类型提示就是这样; hints.提示。 They act as documentation, they don't cast or coerce types into other types.它们充当文档,它们不会将类型强制转换或强制转换为其他类型。

To do so you need为此,您需要

def x(y):
    return int(y)

And now to accurately type hint this function现在要准确键入提示此功能

def x(y: str) -> int:
    return int(y)

Python's type-hinting is purely for static analysis: no type-checking at runtime is done at all. Python 的类型提示纯粹用于静态分析:在运行时根本不进行类型检查。 This will also work:这也将起作用:

x("One")

Your One failed because One does not exist, but this will work:你的One失败了,因为One不存在,但这会起作用:

One = "seventeen"
x(One)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM