def myFunc( str ):
print "str=", str
if str == None:
print "str is None"
else:
print "str is not None, value is:", str
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中多次调用此函数,str为None.但有时,虽然str为None,但测试失败并打印:
str=None
str is not None, value is None
Run Code Online (Sandbox Code Playgroud)
怎么会发生这种情况?
字符串'None'和bytestring 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__))
Run Code Online (Sandbox Code Playgroud)