Lin*_* Ma 4 python string python-2.7
想知道是否if not foo is None一样if foo?使用Python 2.7并且foo是一个字符串.
对于空字符串,两者都不同:
foo = ''
if foo:
print 'if foo is True'
Run Code Online (Sandbox Code Playgroud)
不会打印任何东西,因为它是空的,因此考虑False但是:
if foo is not None:
print 'if not foo is None is True'
Run Code Online (Sandbox Code Playgroud)
将打印,因为foo是不无!
我根据PEP8更改了它.if foo is not None相当于你的,if not foo is None但更具可读性,因此PEP8推荐.
if a is None:
pass
Run Code Online (Sandbox Code Playgroud)
在if将只True如果a = None被明确设置.
另一方面:
if a:
pass
Run Code Online (Sandbox Code Playgroud)
有几种评估方式True:
Python尝试调用a.__bool__,如果实现了这个,则使用返回的值.
None,False,0.0,0将评估为False,因为他们的__bool__方法返回False.如果a.__bool__没有实现,那么它会检查a.__len__.__bool__返回的内容.
'',[],set(),dict(),等将评估为False,因为他们的__len__方法返回0.这是False因为bool(0)是False.如果a.__len__没有实现,那么如果只是返回True.
True.另请参阅:python文档中的真值测试.
小智 5
不,当foo是空字符串时不一样.
In [1]: foo = ''
In [2]: if foo:
...: print 1
...:
In [3]: if foo is None:
...: print 2
...:
In [4]: if not foo is None:
...: print 3
...:
3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11768 次 |
| 最近记录: |