Reference class in class creation

Bruno Desthuilliers onurb at xiludom.gro
Tue Nov 21 08:21:14 EST 2006


Gregor Horvath wrote:
> Hi,
> 
> I want to reference a class itself in its body:
> 
> class SomeElement(object):
> 	def __init__(self, mycontainer):
> 		self.mycontainer=mycontainer	
> 	
> class SomeContainer(object):
> 	a = SomeElement(SomeContainer)

Are you sure you want to
1/ create SomeElement as a *class* attribute (that is, an attribute
shared by all instances of SomeContainer) and
2/ pass the SomeContainer *class* to the initializer of SomeElement ?

Well, anyway:

> 
> Unfortunatly this does not work since the name SomeContainer is not
> definied at class creation time of SomeContainer:

indeed.

> 
> How to do this?
> 
> Unfortunatly the obvious:
> 
> class SomeContainer(object):
> 	def __init__(self):
> 		self.a = SomeElement(SomeContainer)

You do understand that declaring 'a' as an attribute of self creates an
instance attribute, while your above snippet creates 'a' as a class
attribute, do you ?

> is not possible because of other constraints.

Care to elaborate ?

FWIW, there are technical answers to your question (look for descriptors
and/or metaclasses)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list