Want - but cannot get - a nested class to inherit from outer class
marek.rocki at wp.pl
marek.rocki at wp.pl
Sat Mar 8 08:38:43 EST 2008
Everybody has already explained why this doesn't work and a possible
"solution" using metaclasses was suggested. I tried to implement it,
ended up with monkey-patching __bases__, which is certainly an
abomination (will it be possible in python 3.0?) but seems to do the
trick.
class _InheritFromOuterClass(object):
""" This class is used as a marker. """
pass
class MetaFixInheritance(type):
""" This metaclass, along with ordinary class creation, changes base
of
all the inner classes (marked as inheriting from
_InheritFromOuterClass)
to the class being created. """
def __new__(self, name, bases, members):
result = type(name, bases, members)
for member in members.itervalues():
if isinstance(member, type) and issubclass(member,
_InheritFromOuterClass):
member.__bases__ = result,
return result
class Outer(object):
""" Test an inner class inheriting from the outer class. Inheritance
is
monkey-patched upon creation of the outer class. """
__metaclass__ = MetaFixInheritance
class Inner(_InheritFromOuterClass):
pass
def foo(self):
return 'Outer.foo()'
inner = Outer.Inner()
print 'Inner.foo() is in fact', inner.foo()
More information about the Python-list
mailing list