Can't use class variable with private nested class

Alex Martelli aleax at mac.com
Wed Mar 28 01:08:34 EDT 2007


<tron.thomas at verizon.net> wrote:
   ...
> class Outer:
>       class Inner:
>               printOnce = True
> 
>               def __init__(self):
>                       if Outer.Inner.printOnce:
>                               print 'Printing once.'
>                               Outer.Inner.printOnce = False
> 
>       def __init__(self):
>               first = Outer.Inner()
>               second = Outer.Inner()
> 
> outer = Outer()
> 
> 
> However the following code, which has a private nested class, does not
> work:
> class Public:
>       class __Private:
>               printOnce = True
> 
>               def __init__(self):
>                       print 'Creating a __Private instance'
>                       if Public.__Private.printOnce:

When, anywhere "immediately inside" a class named X, you use a name
__foo starting with two underscores, that name is mangled to _X__foo.
Here, you're inside class __Private, so the mangling of __Private is to
_Private__Private (I'd actually have expected more stray underscores
hither and thither, but that's the gist of it).

>                               print 'Printing once.'
>                               Public.__Private.printOnce = False
> 
>       def __init__(self):
>               print 'Creating a Public instance'
>               first = Public.__Private()
>               second = Public.__Private()
> 
> public = Public()
> 
> Attempting to run the code will produce this error:
> AttributeError: class Public has no attribute '_Private__Private'
> 
> What can be done so that this private nested class can have the same
> functionality as the public nested class?

Forget all the naming silliness and use self.__class__.printOnce
instead.


Alex



More information about the Python-list mailing list