Newbie: Truth values (three-valued logic)
Tim Peters
tim_one at email.msn.com
Wed Jun 16 01:21:57 EDT 1999
[Olaf Delgado]
> I am just starting to use python seriously. Currently, I am porting a
> small class library from C++ to python, which is kind of fun. Everything's
> much more simple and elegant now.
Except for C++ <wink>.
> There's one thing I could do in C++, though, which doesn't seem to work in
> python: some methods need to return truth values, which can be 1 for
> 'true', 0 for 'false' and x for 'frankly I don't know'.
> ... [but 'not' only delivers true or false] ...
> As far as I know, the logical negation operator can not be overloaded,
> so I have no chance to change this, right?
Right. I'd try overloading "~" instead (the unary prefix "complement"
operator, special method name __invert__):
>>> class uncertain:
def __nonzero__(self):
return 0
def __repr__(self):
return 'dunno'
def __invert__(self):
return self
>>> maybe = uncertain()
>>> if maybe or ~maybe:
print "maybe or not maybe!"
else:
print "we don't need no stinking excluded middle!"
we don't need no stinking excluded middle!
>>>
Under this hack, may work best if you use 0 to represent false and -1 to
represent true:
>>> ~0
-1
>>> ~-1
0
>>>
OTOH, overloading sucks when you have to fight the language -- and 90% of
the time even when you don't <0.9 wink>.
functions-spelled-as-functions-rarely-confuse-ly y'rs - tim
More information about the Python-list
mailing list