def myFunc( str ):
print "str=", str
if str == None:
print "str is None"
else:
print "str is not None, value is:", str
此函数在我的应用程序中多次调用,str 为 None。然而有时,尽管 str 为 None,但测试失败并打印:
str=None
str is not None, value is None
这怎么会发生?
最佳答案
字符串 'None'
和字节串 b'None'
都将打印出 None,但实际上并不是 none。此外,您可以使用自定义类来覆盖它们的 __str__
方法以返回 'None'
,尽管它们实际上不是 None。
一些审美注意事项:Python 保证只有一个 None
实例,因此您应该使用 is
而不是 ==
。此外,您不应将变量命名为 str
,因为这是内置函数的名称。
试试这个定义:
def myFunc(s):
if s is None:
print('str is None')
else:
print('str is not None, it is %r of type %s' % (s, type(s).__name__))
https://stackoverflow.com/questions/9310841/