Object instance "reporting" to a container class instance

Jordan Greenberg "greenbergj\" at NOSPAM wit.edu
Mon Mar 12 11:35:26 CET 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:


class Something(object):
	def __init__(self, *args):

class Container(object):
	def __init__(self):

	def newinstance(self, newclass, *args):
		return tmp
	def delinstance(self, inst):
a=cont.newinstance(Something, 5, 6)
b=cont.newinstance(Something, 7, 8)
c=cont.newinstance(Something, 8, 9)

print len(cont.instances)

print len(cont.instances)

#note that b is still defined, unless you remove that name explicitly...
print b
del b
print b


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