customizing and/or/not
Hans Nowak
zephyr01 at alltel.net
Tue Aug 12 23:31:46 EDT 2003
Simon Burton wrote:
> Just reading about the new Sets... and this came up.
> Why can't we customize the and/or/not operators?
> I see this as making one's own boolean type.
> Is it possible?
Probably not. The 'and' and 'or' operators are special, in that they do
short-circuit evaluation (as opposed to the binary operators & and |). Even if
it would be possible to define a magic method __land__ or __lor__, they are not
guaranteed to be called. Consider
a and b
...if a is true, then b is never evaluated. A hypothetical call a.__land__(b)
would be impossible without evaluating b first. Ditto for 'or'.
'not' is a different bowl of soup, it *can* be customized using the __nonzero__
magic method:
>>> class Foo:
def __init__(self, value):
self.value = value
def __nonzero__(self):
return not self.value
>>> f = Foo(42)
>>> not f, not not f
(1, 0)
>>> f = Foo([])
>>> not f, not not f
(0, 1)
HTH,
More information about the Python-list
mailing list