class Boolean (v 0.0.2)

Cromwell, Jeremy jcromwell at ciena.com
Sat Jan 12 21:52:23 CET 2002


I agree.  And since they aren't mutable, I added __hash__ (and for fun,
__invert__)

class Boolean:
    def __init__(self, truth=1):
        self.truth = not not truth
    def __eq__(self, other):
        return self.truth != (not other)
    def __str__(self):
        return ["False","True"][self.truth]
    def __repr__(self):
        return "Boolean(%d)" % self.truth
    def __nonzero__(self):
        return self.truth
    def __hash__(self):
        return hash(`self`)
    def __invert__(self):
        return not self.truth

True = Boolean(1)
False = Boolean(0)

## or if that's to plain...
#
# True = Boolean(id(None)==id(None))
# False = Boolean(not True)
#
##

-Jeremy


-----Original Message-----
From: Brian Quinlan [mailto:brian at sweetapp.com]
Sent: Saturday, January 12, 2002 11:36 AM
To: Cromwell, Jeremy; python-list at python.org
Subject: RE: class Boolean (was true = 1)


Jeremy Cromwell wrote:
> class Boolean:
>     def __init__(self, truth=1):
>         self.truth = not not truth
>     def __eq__(self, other):
>         return self.truth != (not other)
>     def __str__(self):
>         return ["False","True"][self.truth]
>     def __repr__(self):
>         return "Boolean(%d)" % self.truth
>     def __len__(self):
>         return self.truth
> 
> true = Boolean(1)
> false = Boolean(0)

You should probably change __len__ to __nonzero__. That way people won't
be fooled into thinking that your class is a container-like thing.

Cheers,
Brian





More information about the Python-list mailing list