class inheritance

Ethan Furman ethan at stoneleaf.us
Tue Dec 21 12:21:17 EST 2010


JLundell wrote:
> On Saturday, March 13, 2010 9:03:36 AM UTC-8, Jonathan Lundell wrote:
>> I've got a subclass of fractions.Fraction called Value; it's a mostly
>> trivial class, except that it overrides __eq__ to mean 'nearly equal'.
>> However, since Fraction's operations result in a Fraction, not a
>> Value, I end up with stuff like this:
>>
>> x = Value(1) + Value(2)
>>
>> where x is now a Fraction, not a Value, and x == y uses
>> Fraction.__eq__ rather than Value.__eq__.
>>
>> This appears to be standard Python behavior (int does the same thing).
>> I've worked around it by overriding __add__, etc, with functions that
>> invoke Fraction but coerce the result. But that's tedious; there are a
>> lot of methods to override.
>>
>> So I'm wondering: is there a more efficient way to accomplish what I'm
>> after?
> 
> I recently implemented a different approach to this. I've got:
> 
> class Rational(fractions.Fraction):
> 
> ... and some methods of my own, including my own __new__ and __str__ (which is one of the reasons I need the class). Then after (outside) the class definition, this code that was inspired by something similar I noticed in Python Cookbook. There are two things going on here. One is, of course, the automation at import time. The other is that the wrapper gets a Fraction instance and simply overrides __class__, rather than creating yet another Rational and unbinding the interim Fraction. Seems to work quite well.

[snip]

Another option is to use a metaclass:

class Perpetuate(ABCMeta):
     def __new__(metacls, cls_name, cls_bases, cls_dict):
         if len(cls_bases) > 1:
             raise TypeError("multiple bases not allowed")
         result_class = type.__new__(metacls, cls_name,
                                     cls_bases, cls_dict)
         base_class = cls_bases[0]
         known_attr = set()
         for attr in cls_dict.keys():
             known_attr.add(attr)
         for attr in base_class.__dict__.keys():
             if attr in ('__new__'):
                 continue
             code = getattr(base_class, attr)
             if callable(code) and attr not in known_attr:
                 setattr(result_class, attr,
                         metacls._wrap(base_class, code))
             elif attr not in known_attr:
                 setattr(result_class, attr, code)
         return result_class
     @staticmethod
     def _wrap(base, code):
         def wrapper(*args, **kwargs):
             if args:
                 cls = args[0]
             result = code(*args, **kwargs)
             if type(result) == base:
                 return cls.__class__(result)
             elif isinstance(result, (tuple, list, set)):
                 new_result = []
                 for partial in result:
                     if type(partial) == base:
                         new_result.append(cls.__class__(partial))
                     else:
                         new_result.append(partial)
                 result = result.__class__(new_result)
             elif isinstance(result, dict):
                 for key in result:
                     value = result[key]
                     if type(value) == base:
                         result[key] = cls.__class__(value)
             return result
         wrapper.__name__ = code.__name__
         wrapper.__doc__ = code.__doc__
         return wrapper


then the actual class becomes:

class CloseFraction(Fraction):
     __metaclass__ = Perpetuate
     def __eq__(x, y):
         return abs(x - y) < 1  # season to taste
     def __repr__(x):
         return "CloseFraction(%d, %d)" % (x.numerator, x.denominator)

Perpetuate needs to handle multiple inheritance better, but it might 
meet your needs at this point.

Sample run:
--> n = CloseFraction(3, 2)
--> n
CloseFraction(3, 2)
--> print n
3/2
--> m = CloseFraction(9, 4)
--> m
CloseFraction(9, 4)
--> n == m
True
--> n - m
CloseFraction(-3, 4)
--> n + m
CloseFraction(15, 4)
--> n.real
CloseFraction(3, 2)
--> n.imag
0  # this is an int

Hope this helps!

~Ethan~



More information about the Python-list mailing list