2012-02-16 35 views
1
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,但测试失败并且它会打印:Python如果检查失败,则为无

str=None 
str is not None, value is None 

这是怎么发生的?

回答

5

字符串'None'和字节串b'None'都将输出None,但实际上不是none。此外,您可以使用自定义类替代__str__方法返回'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__)) 
+2

谢谢,这有帮助。它打印出“str不是无,它是u'None'类型unicode”。这与if检查工作的其他情况不同:“str不是None,它是NoneType的任何类型”。所以问题是什么是'不',我该如何检查。 – Paul 2012-02-16 12:08:09

+1

@Paul不知道你是否已经回答了这个问题,但是对于所有后来进入这个页面的人来说:'u'None''只是一个值为'None'的unicode字符串('u'None'= ='None'' - >'True';'u'None'是'None' - >'False')。所以如果你想检查u'None',你可以检查:'如果mystr是None或str(mystr)=='None'' – 2012-04-30 17:39:00

1

有没有可能str绑定到字符串对象"None"

我会推荐使用if str is None而不是==。更何况,你真的不应该使用str作为变量名称。

+0

THX。我已经重新命名我的变种。仅strover仅用于stackoverflow示例。 – Paul 2012-02-16 12:02:20

2

再次检查的str值。如果您的测试失败,则str不是特殊的None对象。可能str实际上是字符串'None'

>>> str = None 
>>> str == None 
True 
>>> str = 'None' 
>>> str == None 
False 
>>> print str 
None 

从您的意见来看,str实际上是u'None'unicode类型的字符串。你可以测试这样的:

>>> s = unicode('None') 
>>> s 
u'None' 
>>> print s 
None 
>>> s == 'None' 
True 

现在,虽然你可以这样做,我怀疑你的问题在别处。调用代码必须将此对象转换为字符串,例如unicode(None)。如果对象不是None,调用代码最好只转换为字符串。

0

您也可以使用__repr__方法来显示值:

>>> x = None 
>>> print 'the value of x is', x.__repr__() 
the value of x is None 
>>> x = "None" 
>>> print 'the value of x is', x.__repr__() 
the value of x is 'None'