Delegation in Python

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Jan 24 18:59:35 EST 2015


On 24/01/2015 23:41, Gary Herron wrote:
> On 01/24/2015 03:22 PM, Chris Angelico wrote:
>> 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
>
> You can always "monkey-path" the Fraction class on the fly to add a new
> method to it.  I think most would consider this a bad idea, but it does
> work.
> Try this:
>
>  >>> from fractions import Fraction
>  >>> def is_integer(self):
> ...     return self.numerator % self.denominator == 0
> ...
>  >>> Fraction.is_integer = is_integer # Monkey-patch Fraction
>  >>>
>  >>> Fraction(1,2).is_integer()
> False
>  >>> Fraction(2,1).is_integer()
> True
>
>
> Gary Herron
>

As regards this being a bad idea I'd suggest the latest score is 
Practicality 1 Purity 0 :)

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list