I sometimes want an object to be treated as a number. This is what I do:
class C(object):
def __init__(self):
self.a = 1.23
self.b = 'b'
def __float__(self):
return float(self.a)
c = C()
Explicit casting works:
works = float(c) + 3.141
correct_comparison = (float(c) < 1)
>>> correct_comparison
False
However, automatic (implicit) casting doesn't work
wrong_comparison = (c < 1)
>>> wrong_comparison
True
doesnt_work = c + 2.718 #TypeError exception is thrown
Is there a way to perform automatic casting in Python. How bad is this idea?
UPDATE @BrenBarn has pointed me to the "emulating numeric types" section in Python documentation. Indeed, it is possible to define every possible operator, which gives a lot of flexibility, but is also very verbose. It seems that automatic implicit casting is possible only if one defines all the relevant operators. Is there a way to make this less verbose?