[Tutor] "x and y" means "if x is false, then x, else y"??
Peter Otten
__peter__ at web.de
Thu Jul 22 19:42:20 CEST 2010
Lie Ryan wrote:
> On 07/05/10 22:23, Adam Bark wrote:
>
>>
>> I should add that this is how something like:
>>
>> if x != y:
>> do_something()
>>
>> works, if expects a True or False (this isn't always true but works for
>> comparison operators expressions such as this).
>>
>
> <nit> "if" expects an expression that can be converted to True or False
> by calling its __bool__()/__nonzero__(); in case of missing
> __bool__/__nonzero__, then the object is considered True. </nit>
<meta:nit>Don't forget about __len__()</meta:nit>
>>> class A:
... def __init__(self, n): self.n = n
... def __len__(self): return self.n
...
>>> "yes" if A(1) else "no"
'yes'
>>> "yes" if A(0) else "no"
'no'
Bonus:
>>> "yes" if A(-1) else "no"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: __nonzero__ should return >= 0
Peter
More information about the Tutor
mailing list