nested classes

gbreed at cix.compulink.co.uk gbreed at cix.compulink.co.uk
Tue Jun 19 10:21:32 EDT 2001


In article <3B2E4725.535AB18E at sympatico.ca>, 
seefeld at sympatico.ca (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 
'A'.
> In fact, I don't need to qualify them (i.e. 'foo' instead of 
'A::foo'
> for any symbol 'foo' in the scope 'A' is just fine) if I'm 
inside
> that scope, no matter how deeply nested (of course, as long as 
there
> are no ambiguities).

You're correct, I've found an example

<http://oopsla.snu.ac.kr/c++/cpplecture/chap5/node22.html>

and an argument against them

<http://www.elj.com/eiffel/ij/nested-classes/>

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.

Or

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')
A.addNode('B','share')

print A.prefix
print A.B.prefix


Or

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 ;)


                  Graham



More information about the Python-list mailing list