I can use a boolean as a list index:
isTrue = True
print ('No','Yes')[isTrue] -> 'Yes'
but if I define a class,
class YeaOrNay(object):
def __init__(self, val):
self.val = bool(val)
def __nonzero__(self):
return self.val
def __int__(self):
return int(self.val)
def __str__(self):
return ('Nay','Yea')[self.val]
and try to use it the same way:
isTrue = YeaOrNay(True)
print ('No','Yes')[isTrue]
I get an error
TypeError: tuple indices must be integers, not YeaOrNay
I can work around it,
print ('No','Yes')[int(isTrue)] -> 'Yes'
but I would really like to know if there is some magic class method I can add to YeaOrNay to make it ‘just work’.
In python,
boolis a subclass ofint. That’s why you can use aboolas an index of the tuple. However,YeaOrNeais clearly neither and thus the error. If you insist on using this object as an index to a tuple, subclassint(orto trick it to make it work.bool)Otherwise do it the right way.