Python如果检查失败,则无

Pau*_*aul 1 python-2.7

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)

怎么会发生这种情况?

phi*_*hag 5

字符串'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)

  • 谢谢,这有帮助.它打印"str is not None,它是un'ode的'un'ode'".这与if检查有效的其他情况不同:"str不是None,它是NoneType类型的None".所以问题是什么是你'没有',我该如何检查. (2认同)