Delegation in Python

Brian Gladman noone at nowhere.net
Sun Jan 25 00:52:06 CET 2015


On 24/01/2015 23:41, Gary Herron wrote:

[snip]>
> 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

Thanks Gary.  As Chris says, the method he suggests is problematic since
anything delegated returns a Fraction, not an RF.  Patching Fraction
looks nicer to use even if it is frowned on.

   Brian




More information about the Python-list mailing list