Can not x
and x==None
give different answers if x
is a class instance ?
I mean how is not x
evaluated if x
is a class instance ?
yes it can give different answers.
x == None
will call the __eq__()
method to valuate the operator and give the result implemented compared to the None
singleton.
not x
will call the __nonzero__()
(__bool__()
in python3) method to valuate the operator. The interpreter will convert x
to a boolean (bool(x)
) using the mentioned method and then inverse its returned value because of the not
operator.
x is None
means that the reference x points to the None
object, which is a singleton of type NoneType
and will valuate false in comparaisons. The is
operator tests object identity, and thus whether or not the two objects compared are the same instance of an object, and not similar objects.
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
is eqivalent to:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With