Object instance "reporting" to a container class instance
Jordan Greenberg
"greenbergj\" at NOSPAM wit.edu
Mon Mar 12 06:35:26 EDT 2007
Daniel Lipovetsky wrote:
> I would like for an object to "report" to a container object when a
> new instance is created or deleted. I could have a container object
> that is called when a new instance is created, as below.
I've run into a similar problem before, in my case it was easiest to
allow the container to create the new instances, sort of like:
<CODE>
class Something(object):
def __init__(self, *args):
self.x=args
class Container(object):
def __init__(self):
self.instances=[]
def newinstance(self, newclass, *args):
tmp=newclass(args)
self.instances.append(tmp)
return tmp
def delinstance(self, inst):
self.instances.remove(inst)
cont=Container()
a=cont.newinstance(Something, 5, 6)
b=cont.newinstance(Something, 7, 8)
c=cont.newinstance(Something, 8, 9)
print len(cont.instances)
cont.delinstance(b)
print len(cont.instances)
#note that b is still defined, unless you remove that name explicitly...
print b
del b
print b
</CODE>
This can be very, very, very ugly. I don't particularly actually
recommend doing anything like this. Usually you should re-think your
organization to make this unnecessary. I suppose, though, it can come in
handy in certain situations.
-Jordan G
More information about the Python-list
mailing list