212

I'm a bit confused about how/why so many python developers use if not in their conditional statements.

for example, lets say we had a function,

def foo(bar = None):
    if not bar:
        bar = 2

But why go about this way? I mean, wouldn't doing if bar != None or if bar is not Nonebe more explicit? What does if not try to say?

4

1 回答 1

270

是的,if bar is not None更明确,因此更好,假设它确实是你想要的。情况并非总是如此,存在细微差别:if not bar:如果bar是任何类型的零或空容器,或False. 许多人确实使用not bar他们真正的意思bar is not None

于 2013-05-24T16:29:35.100 回答