inner classes in python as inner classes in Java

Alex Martelli aleax at aleax.it
Wed Oct 15 12:14:08 EDT 2003


Carlo v. Dango wrote:
   ...
> init method i introduce the "outer" field.. however, at this point the
> __getattr__ is called which makes me look in the outer scope.. which was
> not the intention. How to do a proper implementation?

I think what's called is __setattr__, NOT __getattr__.  __setattr__ if you
define it is called for EVERY attribute you set by assignment, and there
is no "finding" involved whatsoever.  Do you TRULY want to delegate all
attribute settings, performed on an instance of the innerclass, to the
corresponding 'outer' -- _except_ self.outer?  If so, then the following
should be OK:

class B(object):

  def __init__(self, outer=None):
      # the key issue: bypass B.__setattr__ by delegating to the
      # superclass's (object's) implementation
      object.__setattr__(self, 'outer', outer)

  def foo(self):
      print 'my name is', self.name

  def __getattr__(self, name):
      if self.outer is None:
          raise AttributeError, name
      return getattr(self.outer, name)

  def __setattr__(self, name, value):
      if self.outer is None:
          raise AttributeError, name
      return setattr(self.outer, name, value)

I have taken the occasion to correct other errors you had with
attribute getting and setting, and indent with spaces, not with
tabs (your post was indented with tabs thus unreadable with such
newsreaders as KDE's KNode, Outlook Express, et al: please do
NOT post code indented with tabs, thanks).

It's not very clear to me what you mean to obtain with this
class B, but, in any case, this is how to do this kind of
automatic delegation in Python.


Alex





More information about the Python-list mailing list