繁体   English   中英

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

[英]Difference between 'not x' and 'x==None' in python

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

我的意思是怎么not x ,如果评估x是一个类的实例?

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

x == None

将调用__eq__()方法来评估运算符,并将实现的结果与None单例进行比较。

not x

将调用__nonzero__()__bool__() )方法来评估运算符。 解释器将使用上述方法将x转换为布尔值( bool(x) ),然后因为not运算符而将其返回值反转。

x is None

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

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

not x是等价的:

not bool(x)

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

是; not使用__bool__ (在Python 3中; Python 2使用__nonzero__ ), x == None可以被__eq__覆盖。

(两者都显示在这里。)

如果x正,not x表示否定 ,反之亦然。

x == None指也只会是True ,如果x is NoneTrue否则返回False。 检查一下

正面我的意思是选择了if块。 True也是积极的。

对于各种各样的值, not x ,例如0“”False[]{}等。

x == None仅对一个特定值None为真。

如果x是一个类实例,那么not xx == None都将为false,但这并不意味着它们是等效的表达式。


精细; 前一段应为:

如果x是一个类实例,那么not xx == None都将为false,除非有人正在使用类定义玩愚蠢的bugger。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM