Can't use class variable with private nested class

tron.thomas at tron.thomas at
Wed Mar 28 06:47:56 CEST 2007

The following code will print a message only once:
class PrintOnce:
	printOnce = True

	def __init__(self):
		if PrintOnce.printOnce:
			print 'Printing once.'
			PrintOnce.printOnce = False

first = PrintOnce()
second = PrintOnce()

The following code will do the same thing for a nested class:
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
class Public:
	class __Private:
		printOnce = True

		def __init__(self):
			print 'Creating a __Private instance'
			if Public.__Private.printOnce:
				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?

More information about the Python-list mailing list