Inner classes

Geoffrey Gerrietts geoff at homegain.com
Thu Jun 14 18:26:56 EDT 2001


> From: Isaac To [mailto:kkto at csis.hku.hk]:
>
> No if the original poster wants a Java-style inner class.  Java
> inner class is a rather strange concept.  The idea is for the
> inner class instance to have a reference to the outer class,
> and unlock the namespace of the outer class in methods of the
> inner class.

Sounds like this could be reasonably simulated with a __getattr__
that delegates? An example that seems to implement the
requirement as described, follows.

It depends on what you're looking for, but Python has all the
requisite tools. It's just a question of why you'd /want/ to do
something that absurd. :)

Thanks,
--G.

class Outer:
    class __Inner:
        def __init__(self, container):
            self.__container = container
        def __getattr__(self, attr):
            try:
                res = self.__dict__[attr]
            except KeyError:
                try:
                    res = getattr(self.__class__,attr)
                except AttributeError:
                    res = getattr(self.__container,attr)
            return res

        def f(self, spam):
            return spam + self.g(spam)

    def Inner(*args):
        self = args[-1]
        return self.__Inner(self)

    def g(self, foo):
        return foo * 2

oInst = Outer()
iInst = oInst.Inner()

print oInst.g(5)
print iInst.f(5)

---
Geoff Gerrietts <geoff at homegain.com>
Software Engineer, HomeGain.com
510-655-0800 x4320




More information about the Python-list mailing list