nested classes

gbreed at gbreed at
Tue Jun 19 10:21:32 EDT 2001

In article <3B2E4725.535AB18E at>, 
seefeld at (Stefan Seefeld) wrote:

> uh, what do *you* think that I'm trying to do, then ? :)

Beats me :)

> What I'm arguing about is a matter of name resolution. I sure
> can open a scope 'A' in C++, insert a new scope 'B' into it,
> and from within that access other symbols declared in scope 
> In fact, I don't need to qualify them (i.e. 'foo' instead of 
> for any symbol 'foo' in the scope 'A' is just fine) if I'm 
> that scope, no matter how deeply nested (of course, as long as 
> are no ambiguities).

You're correct, I've found an example


and an argument against them


But my head still spins when I try to think of a C++ class that 
hasn't been instantiated.  C++'s nested classes seem to be a 
special case of what Java's inner classes do, so check the 
thread on those.

Here's another try:

class A:
  def __init__(self):
    self.prefix = 'usr/local'
  class __B:
    def __init__(self, parent):
      self.prefix = os.path.join(parent.prefix, 'share')
  def B(self):
    return self.__B(self)

print A().prefix
print A().B().prefix

You could remember the parent, but that'd lead to a circular 
reference (not such a bad thing for 2.x).

Which means the same purpose would be served by

class FileNode:
  """holds a prefix"""

A = FileNode()
A.prefix = 'usr/local'
A.B = FileNode()
A.B.prefix = os.path.join(A.prefix,'share')

print A.prefix
print A.B.prefix

No problem about the namespace, because it's always explicit.


class FileNode:
  def __init__(self, prefix):
    self.prefix = prefix
  def addNode(self, name, prefix):
    setattr(self, name,
        FileNode(os.path.join(self.prefix, prefix)))

A = FileNode('usr/local')

print A.prefix
print A.B.prefix


class FileNode:
  def __init__(self, prefix):
    self.prefix = prefix
  def newChildNode(self, prefix):
    return FileNode(os.path.join(self.prefix, prefix))

A = FileNode('usr/local')
A.B = A.newChildNode('share')

print A.prefix
print A.B.prefix

Perhaps if you give us C++ code of what you're trying to do, we 
can tell you why you don't need to do it ;)


More information about the Python-list mailing list