[Tutor] Re: Python vs. Ruby
Abel Daniel
abli at freemail.hu
Fri Oct 31 00:30:19 EST 2003
Gregor Lingl writes:
> On the other hand there are types of objects, e.g. type 'function',
> which cannot be subclassed as far as I know (and regret).
>
> Testtask: is it possible to subclass (numerical) functions - say this
> new class is named Fun - e.g. by adding a __add__ method, in a
> way that their instances can be added, like:
> >>> from math import sin, cos
> >>> f = Fun(sin) + Fun(cos) ### see remark below
> >>> f(1)
> #### should output sin(1)+cos(1)
> In short: it would be nice to create some sort of function algebra.
>
> In Python this seems a bit weird because of the special
> way functions are defined (namely via the reserved word def).
> So how should (or could) one define a "fun"? Maybe by making
> it "callable" somehow? (Oh, I feel that this is not a very sharply
> defined problem ...)
Well, here is a shot at it:
class Fun:
def __init__(self, func):
self.func=func
def __call__(self, *a, **kw):
return self.func(*a, **kw)
def __add__(self, other):
def f(*a, **kw):
return self.func(*a, **kw) + other(*a, **kw)
return Fun(f)
>>> from math import sin, cos
>>> fc=Fun(cos)
>>> fs=Fun(sin)
>>> fcs=fc+fs
>>> fc(1)+fs(1)
1.3817732906760363
>>> fcs(1)
1.3817732906760363
>>>
Finishing up (adding other stuff from
http://python.org/doc/current/ref/numeric-types.html
and handling things like "Fun(math.sin) + 5" ) are left as an exercise
to the reader. :)
Of course Fun instances won't be functions, but the interface is the same
(they can be called), so it shouldn't matter.
--
Abel Daniel
More information about the Tutor
mailing list