[英]Does this Python expression make sense?
I found this kind of expression several times in a python program: 我在python程序中多次发现这种表达式:
if variable is not None:
dothings(variable)
It seems strange to me, and I think that it has no more sense than: 这对我来说似乎很奇怪,我认为它没有比以下更有意义了:
if variable:
dothings(variable)
Maybe I don't know Python enough, and the expression is explained somewhere? 也许我不太了解Python,并且表达式在某处被解释了?
variable
could be 0
, or False
, or []
, or ()
; variable
可以是0
,或False
,或[]
,或()
; be 'falsy' in other words, and then the if
statement would be skipped. 换句话说是“虚假”,然后会跳过
if
语句。
See Truth testing for more detail on what is considered false in a boolean context. 有关布尔上下文中被视为false的更多详细信息,请参阅真值测试 。
In short, testing if variable is not None
allows variable
to be anything else , including values that would otherwise be considered False in a boolean context. 简而言之,测试
variable is not None
允许variable
为其他任何东西 ,包括在布尔上下文中否则将被视为False的值。
Some values are falsy , but are not None
. 有些值是假的 ,但不是
None
。 You may still want to dothings()
to those values. 您可能仍希望将
dothings()
为这些值。
Here are the things that are falsy in Python 2. (You may want to change the '2' in the URL to a '3' to get the values for Python 3, but it didn't change much.) 以下是Python 2中伪造的东西。 (您可能希望将URL中的'2'更改为'3'以获取Python 3的值,但它没有太大变化。)
Eg 例如
i = 0
if i is not None:
print i # prints i
if i:
print i # prints nothing
In the google voice python implementation I came across this as well, their use was during a function call. 在谷歌语音python实现中,我也遇到了这个问题,他们的使用是在函数调用期间。 The parameters are defaulted to "None" and then when the function is called they can check if the values are changed or the default.
参数默认为“None”,然后在调用函数时,它们可以检查值是否更改或默认值。 IE
IE
def login (user=None, password=None)
if user is None:
user = input('Please enter your username');
...
return <something>;
called by 叫做
login()
OR 要么
login(user='cool_dude')
OR 要么
any combination of user/password you wish. 您希望的任何用户/密码组合。
Additionally your "update" of the logic implies that variable == true or false. 此外,您对逻辑的“更新”意味着变量== true或false。 That is not correct for all cases (it may work in some cases but I'm throwing them out, since it's not a general case).
这对于所有情况都不正确(它可能在某些情况下有效,但我把它们扔掉了,因为它不是一般情况)。 What you are testing by using the "NONE" logic is whether the variable contains anything besides NONE.
您使用“NONE”逻辑测试的是变量是否包含除NONE之外的任何内容。 Similar to what I was saying above, all the "login function" was doing was determining if the user passed anything, not whether the value was valid, true, etc.
类似于我上面所说的,所有“登录功能”正在做的是确定用户是否传递了任何东西,而不是值是否有效,是否等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.