Reference class in class creation

Éric Daigneault daigno at gmail.com
Tue Nov 21 14:45:11 EST 2006


>class Foo(object):
>    me = None
>    def __init__(self):
>       Foo.me = self
>
>easy!
woah... not that made me skip a heartbeat or two..

careful here

easily bitten more like...

Doing this is an assured trap as the Foo.me will change at EVERY instantiation of a new object..  Kinna like taking the singleton concept and turning it`s skin inside out...  


/Vade retro satana/...  oh the insanity..  Reminds me of the Abstract Singleton pattern I once saw in my boss's code...took me a while to recover ;-)...

Now for the problem at hand...



"Gregor Horvath" <gh at gregor-horvath.com> wrote in message 
news:a1b59$4562eff8$547078de$21737 at news.chello.at...

> > Hi,
> >
> > I want to reference a class itself in its body:
>   
For the class itself you could do something like this :

class Foo(object):
    me = None
    def __init__(self):
       Foo.me = self.__class__

again the Foo.me is reinitialized at every instantiation which is not very optimal it is, tho, more predictable.


> >
> > class SomeElement(object):
> > def __init__(self, mycontainer):
> > self.mycontainer=mycontainer
> >
> > class SomeContainer(object):
> > a = SomeElement(SomeContainer)
>   
But looking at your sample here I fear that is not what you are after.  
If I understand correctly what you want is to be able to reference the 
container from the element.  One way of doing so could be

 class SomeElement(object, containerInstance):
 	def __init__(self, containerInstance):
 		self.mycontainer=containerInstance

 class SomeContainer(object):
 	a = SomeElement(self)


that way if you want the class of the container you can always do 
something like :

 <in class SomeElement>
def getContainerClass(self):
    return self.mycontainer.__class__

That`s what so great about Python...  You don`t need a scalpel to spill 
it`s guts on the table :-)

Hope this helps

cheers

Eric :D.



More information about the Python-list mailing list