Wednesday, January 5, 2011

making your class work with built-in math functions

Just add __float__ and/or __int__.  Then the built-in math functions, or anything that sanitizes its input via int() or float() will see your objects as a numeric type.


>>> import math

>>> class B(object):
...    def __float__(self): return 0.5
...
>>> math.sin(B())
0.47942553860420301

No comments:

Post a Comment