python中'not x'和'x == None'之间的区别

Nin*_*420 9 python

可以not xx==None给出不同的答案,如果x是一个类的实例?

我的意思是如何not x评估是否x是一个类实例?

zmo*_*zmo 12

是的它可以给出不同的答案.

x == None
Run Code Online (Sandbox Code Playgroud)

将调用该__eq__()方法来评估运算符并将结果与None单例进行比较.

not x
Run Code Online (Sandbox Code Playgroud)

将调用__nonzero__()(__bool__()在python3中)方法来评估运算符.解释器将使用上述方法转换x为boolean(bool(x)),然后因not操作符而反转其返回值.

x is None
Run Code Online (Sandbox Code Playgroud)

表示引用x指向None对象,该对象是类型的单例,NoneType并将在comparaisons中评估为false.的is操作者的测试对象的标志,因此不论是否比较的两个对象是相同的对象的实例,并且不相似的对象.


Ash*_*ary 5

class A():
    def __eq__(self, other):  #other receives the value None
        print 'inside eq'
        return True
    def __nonzero__(self):    
        print 'inside nonzero'
        return True
...     
>>> x = A()
>>> x == None      #calls __eq__
inside eq
True
>>> not x          #calls __nonzero__
inside nonzero
False
Run Code Online (Sandbox Code Playgroud)

not x相当于:

not bool(x)
Run Code Online (Sandbox Code Playgroud)

py 3.x:

>>> class A(object):
        def __eq__(self, other):    #other receives the value None
                print ('inside eq')
                return True
        def __bool__(self):    
                print ('inside bool')
                return True
...     
>>> x = A()
>>> x == None       #calls __eq__
inside eq
True
>>> not x           #calls __bool__ 
inside bool 
False
Run Code Online (Sandbox Code Playgroud)