Delegation in Python

Chris Angelico rosuav at gmail.com
Sat Jan 24 18:22:10 EST 2015


On Sun, Jan 25, 2015 at 9:57 AM, Brian Gladman <noone at nowhere.net> wrote:
> But I am not clear on how to delegate from my new class to the existing
> Fraction class.  This is what I have:
>
> --------------------------
> class RF(Fraction):
>
>   def __new__(self, x, y):
>     super().__new__(self, x, y)
>
>   def is_integer(self):
>     return self.numerator % self.denominator == 0
>
>   def __getattr__(self, attr):
>     return getattr(self, attr)

If you just drop everything but your new method, it should work just fine.

class RF(Fraction):
    def is_integer(self):
       return self.numerator % self.denominator == 0

However, this doesn't ensure that operations on RFs will return more
RFs - they'll often return Fractions instead. There's no easy fix for
that, sorry.

ChrisA



More information about the Python-list mailing list