[Python-3000] Fixing super anyone?
Guido van Rossum
guido at python.org
Wed Apr 25 20:33:59 CEST 2007
On 4/24/07, Steven Bethard <steven.bethard at gmail.com> wrote:
> class Super(object):
> def __init__(self, type, obj=None):
> if isinstance(obj, Super):
> obj = obj.__obj__
> self.__type__ = type
> self.__obj__ = obj
> def __get__(self, obj, cls=None):
> if obj is None:
> raise Exception('only supports instances')
> else:
> return Super(self.__type__, obj)
> def __getattr__(self, attr):
> mro = iter(self.__obj__.__class__.__mro__)
> for cls in mro:
> if cls is self.__type__:
> break
> for cls in mro:
> if attr in cls.__dict__:
> x = cls.__dict__[attr]
> if hasattr(x, '__get__'):
> x = x.__get__(self, cls)
> return x
> raise AttributeError, attr
>
> class autosuper(type):
> def __init__(cls, name, bases, clsdict):
> cls.__super__ = Super(cls)
>
> class A:
> __metaclass__ = autosuper
> def f(self):
> return 'A'
>
> class B(A):
> def f(self):
> return 'B' + self.__super__.f()
>
> class C(A):
> def f(self):
> return 'C' + self.__super__.f()
>
> class D(B, C):
> def f(self):
> return 'D' + self.__super__.f()
>
> assert D().f() == 'DBCA'
But:
class E(D): pass
print E().f()
This prints DDBCA which surely isn't right.
Sounds like the classic bug in such attempts.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-3000
mailing list