![](/img/trans.png)
[英]python difference between (x is not None) and (y is not None) and (x and y) is not None
[英]Difference between 'not x' and 'x==None' in python
如果x
是一个类实例, not x
和x==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 None
是True
否则返回False。 检查一下 。
正面我的意思是选择了if
块。 True
也是积极的。
对于各种各样的值, not x
,例如0 , 无 , “” , False , [] , {}等。
x == None
仅对一个特定值None为真。
如果x是一个类实例,那么not x
和x == None
都将为false,但这并不意味着它们是等效的表达式。
精细; 前一段应为:
如果x是一个类实例,那么not x
和x == None
都将为false,除非有人正在使用类定义玩愚蠢的bugger。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.