Delegation in Python

Brian Gladman noone at
Sun Jan 25 08:49:12 CET 2015

On 25/01/2015 00:28, Chris Angelico wrote:
> On Sun, Jan 25, 2015 at 11:18 AM, Brian Gladman <noone at> wrote:
>> Is there a way of doing delegation rather than sub-classing?
>> That is, can I create a class (say RF) that passes some of its methods
>> to Fraction for implementation but always returns an RF?
> Hmm. The key here is that you want more than just delegation; you want
> to transform every return value. That's not going to be easy. It would
> be easiest and cleanest to skip the whole thing, and have a separate
> function for what you're doing here - not a method, a stand-alone
> function.
> def is_integer(fr):
>     return fr.numerator % fr.denominator == 0
> Next best would be the monkey-patching option. Delegation with
> transformation is a lot of effort for what you want.

Thanks, a part of this was a wish to understand how to map what I can do
in other languages into Python.  I felt that it might just be possible
in Python to avoid having to wrap all the methods of the base class in
the derived class.  But it seems that __getattr__ etc are not quite as
magic as I hoped.

Thanks again for your help.


More information about the Python-list mailing list