Python “变量”或“变量不是无”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15652427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:38:07  来源:igfitidea点击:

'variable' or 'variable is not None'

pythoncomparison

提问by NIlesh Sharma

Variable = None

Is there any difference between these three in a specific scenario ? if there is no difference which one is more suitable to use?

在特定场景中这三者之间有什么区别吗?如果没有区别,哪个更适合使用?

if Variable:
 print "Hello world"

and

if Variable is not None:
 print "Hello world"

and

if Variable != None:
 print "Hello world"

are same in case of None Variable ?

在无变量的情况下相同吗?

采纳答案by abarnert

Is there any difference between these three in a specific scenario ?

在特定场景中这三者之间有什么区别吗?

The first asks whether the variable is anything falsy. This test will fail for all kinds of things besides NoneFalse, 0, any empty sequence, etc.

第一个询问变量是否为假。除了NoneFalse0、任何空序列等之外,此测试对于所有类型的东西都会失败。

The second asks whether it's the magic singleton constant None. This will fail only for Noneitself.

第二个询问它是否是神奇的单例常量None。这只会为None自己失败。

The third asks whether it's anything that considers itself equal to None. This will fail for, say, Holder(None), where Holderis a wrapper class whose instances compare equal to whatever they're holding. Or, to give a less realistic but shorter to code exmaple:

第三个询问是否有任何东西认为自己等于None。这将失败,例如,Holder(None)whereHolder是一个包装类,其实例比较等于它们所持有的任何东西。或者,给出一个不太现实但更短的代码示例:

class Stupid(object):
    def __ne__(self, other):
        return False
Variable = Stupid()

The last one is rarely useful; in fact, if you ever think you might need to check == Noneor != None, and you haven't specifically been creating transparent-wrapper classes or anything like that, you probably actually wanted is Noneor is not None. But the other two are both very useful and common.

最后一个很少有用。事实上,如果您认为您可能需要检查== Noneor != None,并且您还没有专门创建透明包装类或类似的东西,那么您可能实际上想要is Noneor is not None。但另外两个都非常有用和常见。

if there is no difference which one is more suitable to use?

如果没有区别,哪个更适合使用?

Well, there isa difference, and which one is more suitable depends on the specific use.

嗯,有区别的,哪个更合适,要看具体的用途了。

At the end of the question, it seems like you might be asking whether there's any difference in the specific case where Variableis definitely None. In that case, of course there is no functional difference between the three.* All of them are guaranteed to be false, and therefore do nothing. Which means there's also no difference between any of the three and writing no code at all. Which is a lot simpler, more readable, and faster.

在问题的最后,您似乎会问在特定情况下是否有任何区别 where Variableis absolute None。在那种情况下,这三者之间当然没有功能上的区别。*它们都保证是假的,因此什么都不做。这意味着三者中的任何一个和根本不编写代码之间也没有区别。这更简单,更易读,更快。

* There is a performance difference—the first one doesn't have to LOAD_CONSTthe None, or call a comparison operator. And, even if you've somehow managed to rebind Noneor change the value of the Noneconstant (maybe by stomping all over the heap with ctypes?), the first one is more likely to still work. But neither of these is ever going to matter—and, if they do, again, no code at all will be even faster and more reliable.

*有一个性能差的第一个不具有LOAD_CONSTNone,或者叫一个比较操作。而且,即使您以某种方式设法重新绑定None或更改了None常量的值(也许通过用ctypes?在整个堆上踩踏?),第一个更有可能仍然有效。但这些都无关紧要——而且,如果它们再次发生,那么根本没有任何代码会更快、更可靠。

回答by Stjepan Bakrac

not xwill be true if xis None, False, [], {}, etc.

not x将真,如果xNoneFalse[]{},等。

x is not Nonewill always be True, unless a variable is actually None.

x is not None将始终是True,除非变量实际上是None

Edit:

编辑:

This is of practical importance, whenever you want to check if a variable is actually set to a proper value. Otherwise you can run into problems. For example, if you want to evaluate a list of items and do:

每当您想检查变量是否实际设置为正确值时,这都具有实际重要性。否则,您可能会遇到问题。例如,如果要评估项目列表并执行以下操作:

if not x:

to check if a list was provided, then the condition will trigger on an empty list, which may still be a valid input. So in that case, you'd like to check with

检查是否提供了列表,则条件将在空列表上触发,该列表可能仍然是有效输入。所以在这种情况下,你想检查

if x is not None:

to allow empty lists as valid inputs, but still check the case that no list at all was provided.

允许空列表作为有效输入,但仍然检查根本没有提供列表的情况。

The Nonevalue as such is comparable to a nullor nilvalue in certain languages. It's a placeholder for the lack of a value in a defined variable (if it is undefined, it will throw a NameError). That's why the Nonevalue is used as a default value in some cases:

None作为这样的值是可比的nullnil在某些语言中值。它是已定义变量中缺少值的占位符(如果未定义,它将抛出 a NameError)。这就是为什么None在某些情况下将该值用作默认值的原因:

>>> def foo():
...     pass
...
>>> x = foo()
>>> x is None
True

It's also frequently used as a default value for optional variables:

它也经常用作可选变量的默认值:

>>> def foo(bar=None):
...     if bar is None:
...         print('No argument passed.')
...     else:
...         print('Variable bar: %s' % str(bar))
...
>>> foo(0)
Variable bar: 0
>>> foo()
No argument passed.

This way, 0is still a valid value, that would evaluate to Falseif checked with if not bar:.

这样,0仍然是一个有效值,False如果使用if not bar:.

回答by jamylak

They are different. notchecks if bool(var)evaluates to False.

它们是不同的。not检查是否bool(var)评估为False

eg.

例如。

>>> not ''
True
>>> not 'abc'
False
>>> not 0
True

if x is Nonechecks if x is Noneitself.

if x is None检查 x 是否是None它本身。

回答by Raymond Hettinger

The official PEP 8 recommendationis to test for Nonewith an identity check:

官员PEP 8的建议是测试与身份检查:

if Variable is not None:
    print "Hello world"

The equality/inequality test would also work but would be slower and non-idiomatic:

相等/不等式测试也可以使用,但速度较慢且不符合习惯:

if Variable != None:
    print "Hello world"

Testing the boolean value of the Variableproduces a different result. The following test would print "hello world" if the variable were an empty container or a number equal to zero:

测试变量的布尔值会产生不同的结果。如果变量是空容器或等于零的数字,以下测试将打印“hello world”:

# Hello world won't print for any of these values:
for Variable in (), '', u'', {}, [], 0, 0.0, 0j, None:
    if Variable:
        print "Hello world"