简体   繁体   English

使用Python断言 - 如何检查输入是否为整数?

[英]Assert using Python- How do I check if the input is Integer or not?

I wrote a function, which gets a number as an input. 我写了一个函数,它将一个数字作为输入。 For example: 例如:

def return_it_back(n):
    return n

I simply need to check if the input is integer or not with assert . 我只需要使用assert检查输入是否为整数。 So, I wrote a test function: 所以,我写了一个测试函数:

def test():
    assert return_it_back("k"), "incorrect input"
test()

Python doesn't show "incorrect input". Python没有显示“输入错误”。 Doesn't the assert return_it_back("k"), "incorrect input" need to print the "incorrect input"? 断言return_it_back(“k”),“输入错误”是否需要打印“错误输入”?

assert condition, message is just syntactic sugar for: assert condition, message只是语法糖:

if not condition:
    raise AssertionError(message)

In your code, return_it_back() just returns it's argument, so 在你的代码中, return_it_back()只返回它的参数,所以

assert return_it_back(n), message

is equivalent to 相当于

assert n, message

which is equivalent to 这相当于

if not n:
    raise AssertionError(message)

so what's get tested is the truth value of n , whatever it is. 所以测试的是n的真值,无论它是什么。

In Python, all objects have a boolean value - empty collections (builtin ones at least), the empty string, numerical zeros and None having a false value and most other objects having by default a true value. 在Python中,所有对象都有一个布尔值 - 空集合(至少是内置的),空字符串,数字零和None错值,大多数其他对象默认为真值。

IOW, unless n is an empty collection, empty string, numerical zero or None it will eval to True and the assertion will succeed. IOW,除非n是一个空集合,空字符串,数字零或None它将eval为True并且断言将成功。

If you want to test whether an object is of a given class (or list of classes), you can use isinstance(obj, cls) (or isinstance(obj, cls, othercls, etc) ). 如果要测试对象是否属于给定类(或类列表),可以使用isinstance(obj, cls) (或isinstance(obj, cls, othercls, etc) )。 Typechecking arguments is usually considered unpythonic (as long as the object acts as expected, who cares what type it is, AKA duck typing ), but there are a couple places where it makes sense - when sanitizing user inputs, at subsystems boundary, and eventually when it's garanteed that any other type will break the function one way or another. Typechecking参数通常被认为是unpythonic(只要对象按预期运行,谁关心它是什么类型,AKA 鸭子打字 ),但有几个地方有意义 - 清理用户输入,在子系统边界,并最终当保证任何其他类型都会以这种或那种方式破坏功能时。

Also, assert is a coder tool, not something to use for arguments validation - if your code is compiled with the --optimize flag for example assert statements will be ignored. 此外, assert是一个编码器工具,而不是用于参数验证的东西 - 如果您的代码是使用--optimize标志编译的,例如断言语句将被忽略。 IOW it's fine for unittesting (but there are more advanced tools in the unittest package) or debugging but not for production code. Iow它适用于单元测试(但是在unittest包中有更高级的工具)或调试但不适用于生产代码。 If you really want to prevent your function from accepting anything but ints you should raise a TypeError (or a ValueError if for example you expect a positive integer and get a negative one) instead. 如果你真的想阻止你的函数接受除了int之外的任何东西,你应该引发一个TypeError (或者如果你想要一个正整数而得到一个负数,则会引入一个ValueError )。

There are several ways, one might be 有几种方法,一种可能

def return_it_back(n):
    assert type(n) == int, "Incorrect input"
    return n

return_it_back(123)
return_it_back('123')

This will obviously break on the second attempt. 这显然会在第二次尝试时中断。


You can also check the return value as in your attempt with 您还可以在尝试时检查返回值

 def return_it_back(n): return n assert type(return_it_back(123)) == int, "Incorrect input" assert type(return_it_back('123')) == int, "Incorrect input" 

but this is redundant and therefore not considered "pythonic". 但这是多余的,因此不被视为“pythonic”。 Take the first alternative. 采取第一种选择。

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

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