Inner classes
Isaac To
kkto at csis.hku.hk
Fri Jun 15 03:23:06 EDT 2001
>>>>> "Geoffrey" == Geoffrey Gerrietts <geoff at homegain.com> writes:
Geoffrey> Sounds like this could be reasonably simulated with a
Geoffrey> __getattr__ that delegates? An example that seems to implement
Geoffrey> the requirement as described, follows.
Or something like the following. Things get rather funny... (and absurd.)
Anyway, I don't like inner class: it makes things much more difficult to
follow. I attribute its existence not to the lack of multiple inheritance,
but to the lack of "friend". (Well... friend's are sometimes useful.) A
Java inner class can use all the private fields of its outer class. Were
the "inner" class a normal class with a reference to the outer class, the
programmer would have to use package access for those fields of "outer"
needed by "inner". In C++, we would make "inner" a friend of the "outer".
But Java's idea of access control is much more coarse-grained.
However, there is no access control in Python, so the use of inner class in
Python is... you guess it.
# Mixin
class Inner:
def __init__(self, container):
self.__container = container
def __getattr__(self, attr):
return getattr(self.__container,attr)
class Outer:
def __init__(self, v):
self.v = v
class __MyInner(Inner):
def __init__(self, container, val):
Inner.__init__(self, container)
self.val = val
def f(self):
return self.g() + self.v + self.val
def getInner(self, val):
return Outer.__MyInner(self, val)
def g(self):
return self.v
oInst = Outer(4)
iInst = oInst.getInner(2)
print oInst.g()
print iInst.f()
More information about the Python-list
mailing list