Declaring a class level nested class?

Jean-Michel Pichavant jeanmichel at sequans.com
Thu Dec 3 07:52:41 EST 2009


cmckenzie wrote:
> Hi.
>
> I'm new to Python, but I've managed to make some nice progress up to
> this point. After some code refactoring, I ran into a class design
> problem and I was wondering what the experts thought. It goes
> something like this:
>
> class module:
>    nestedClass
>
>    def __init__():
>       self.nestedClass = nested()
>       print self.nestedClass.nestedVar
>
>    class nested():
>       nestedVar = 1
>       def __init__(self):
>          print "Initialized..."
>
> I can't figure out what the correct way to construct the "nested"
> class so it can belong to "module".
>
> I want a class level construct of "nested" to belong to "module", but
> I keep getting nestedClass isn't defined.
>
> My example isn't great or 100% accurate, but I hope you get the idea.
>
> Thanks.
>   
class module:

   class nested:
      nestedVar = 1
      def __init__(self):
         print "Initialized..."

   def __init__(self):
      self.nestedClass = module.nested()
      print self.nestedClass.nestedVar

Python will not look into the current class scope when trying to resolve 
"nested", that is why the explicit call including the scope is required.
The code above runs fine with python 2.5.

Jean-Michel




More information about the Python-list mailing list