What use is this class?
Laura Creighton
lac at openend.se
Sun Nov 29 19:00:08 EST 2015
In a message of Sun, 29 Nov 2015 13:36:58 -0800, fl writes:
>Hi,
>
>When I search around tutorial about None, I came across this link:
>
>http://jaredgrubb.blogspot.ca/2009/04/python-is-none-vs-none.html
>
>I don't understand what use of this class example:
>
>
>
>>>> class Zero(): # a class that is zero
>... def __nonzero__(self):
>... return False
>
>
>I can only get the following code running:
>
>cz1=Zero()
>cz1.__nonzero__()
>Out[119]: False
>
>
>Here are my questions:
>1. Is there any other means to use class Zero?
>2. What connection to None on the original author's intention?
The person who wrote this was curious as to why PEP 8 says:
"Comparisons to singletons like None should always be done
with 'is' or 'is not', never the equality operators."
He wrote this class to play around with, to see if it really made
a difference whether you write:
if x is None:
vs
if x == None:
and it does. A class is free to implement its own version of '==' if
if likes, and there, 'being equal to None' might means something
complicated and crazy. People who are just testing against None will
burn their fingers if they use '==' there.
Also its a bad problem when porting code to Jython.
A java null is supposed to be None.
But using '==' will call the underlying .equals method.
If you call that on a null, Java will spit out a Null Pointer Exception.
Laura
More information about the Python-list
mailing list