Can I define nested classes in Python?

Jp Calderone exarkun at intarweb.us
Thu Apr 10 18:58:00 EDT 2003


On Thu, Apr 10, 2003 at 03:32:01PM -0700, sdieselil wrote:
> Hi
> 
> Can I define nested classes in Python and what access do they have to outer
> classes?

  You can, though you might be surprised by their behavior:

    >>> class Foo:
    ...   class Bar:
    ...     pass
    ... 
    >>> print Foo.Bar.__name__
    Bar

  As well as:

    >>> class Foo: 
    ...   class Bar:
    ...     def __init__(self):
    ...       self.container = Foo()
    ... 
    >>> Foo.Bar()
    <__main__.Bar instance at 0x8165364>

  But not:

    >>> class Foo:
    ...   class Bar:
    ...     container = Foo()
    ... 
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 2, in Foo
      File "<stdin>", line 3, in Bar
    NameError: name 'Foo' is not defined

  The reasons for this are perfectly reasonable, of course - the name is not
bound to the class object until the entire class suite has executed.

  It may be reasonable to need access to the outer class in the inner
class's suite (I haven't decided yet), and I recently wrote this to
demonstrate how one might go about achieving this:

  http://intarweb.us:8080/evil/inner_inheritance.py

  HTH,

  Jp

--
"If you find a neighbor in need, you're responsible for serving that
neighbor in need, you're responsible for loving a neighbor just like you'd
like to love yourself." -- George W. Bush, Sept. 16, 2002
-- 
 up 21 days, 19:01, 2 users, load average: 1.13, 1.16, 1.30





More information about the Python-list mailing list