Data Types
Chris Angelico
rosuav at gmail.com
Thu Sep 22 11:27:55 EDT 2016
On Thu, Sep 22, 2016 at 10:33 PM, BartC <bc at freeuk.com> wrote:
>>> print (10<20) => True
>>> print (type(10<20)) => <class 'bool'>
>>
>>
>> 10<20 shouldn't be thought of as some alternative value which is a bool,
>> any
>> more than we should think of 1+1 as being a different value to 2.
>
>
> They're a little different:
>
> 1+1 yielding 2 is int+int => int
> 10<20 yielding True is int<int => bool
That's a couple of example expressions and the way they're handled.
> My post was really about bool values lurking everywhere not just where you
> explicitly write or assign True or False.
Sure. Thing is, those expressions are actually just syntactic sugar
for functions. Let's replace the integers with these puppies:
class Spam:
def __init__(self, value):
self.value = value
def __repr__(self):
return "Spam(%r)" % self.value
def __add__(self, other):
return Spam(self.value + other.value)
def __lt__(self, other):
if self.value < other.value:
return "Yes, %r < %r" % (self.value, other.value)
return ""
>>> Spam(1) + Spam(1)
Spam(2)
>>> Spam(10) < Spam(20)
'Yes, 10 < 20'
>>> Spam(10) > Spam(20)
''
This is perfectly legal code, and it doesn't use True or False for its
comparisons. If you want it to, you have to actually return one of
those constants from __lt__, either by explicitly typing its name, or
by passing it up the chain (eg "return self.value < other.value"),
which just moves the problem around.
ChrisA
More information about the Python-list
mailing list