[Python-3000] Fixing super anyone? (redux)

Joel Bender jjb5 at cornell.edu
Wed Apr 25 16:44:15 CEST 2007


> But I haven't figured out how to do that yet...

It turns out to be easier than I thought, and it avoids changing the 
object __class__, which is ugly.

     class _super(property):
         def __init__(self):
             property.__init__(self, self.get_super, None, None)

         def get_super(self, klass):
             class wrapper:
                 def __getattr__(self, fn):
                     for cls in klass.__mro__[1:]:
                         f = getattr(cls, fn, None)
                         if f:
                             return f

                     raise AttributeError, fn

             return wrapper()

     class _superable(type):
         __super__ = _super()

     class W(object):
         __metaclass__ = _superable

         def f(self):
             print "W"

     class X(W):
         def f(self):
             print "X"
             X.__super__.f(self)

     class Y(W):
         def f(self):
             print "Y"
             Y.__super__.f(self)

     class Z(X, Y):
         def f(self):
             print "Z"
             Z.__super__.f(self)

I'll go back to lurking now...


Joel


More information about the Python-3000 mailing list