Preventing direct access to a class

Daniel Klein danielk at aracnet.com
Sun Feb 4 12:53:33 EST 2001


I have a situation where I need to prevent direct access to a class. IOW, the
only way I wish a class to be instantiated is via another class. For example

>>> class A:
	pass

>>> class B:
	def foo(self):
		return A()
	
>>> b = B()
>>> a = b.foo()

...and there might be other classes that 'return A()'.

I do not want the user to be allowed to do this...

>>>a = A()

It doesn't look like classes can be made 'private to the module' as I tried to
define class A as 'class __A'. The user could still access with a=__A() (no
mangling needed).

Other than placing some convoluted logic in each class, is there a way to
accomplish this pythonic-ly?

Thanks,
Daniel Klein



More information about the Python-list mailing list