how to keep one instance???

Heiko Wundram heikowu at ceosg.de
Tue May 18 08:31:02 EDT 2004


Am Dienstag, 18. Mai 2004 09:31 schrieb BruceKL WhoH:
> So, how to prevent the other instance from running? and how could the
> second instance pass some information to the first one? Any helps are
> appreciated.

If it's Python object instances you're talking about, a little __new__ magic 
can do exactly what you want.

import weakref

class Test(object):

	__classCache = {}

	def __new__(cls,filename):
		inst = None
		if filename in cls.__classCache:
			inst = cls.__classCache[filename]()
		if inst is not None:
			return inst
		inst = object.__new__(cls)
		cls.__classCache[filename] = weakref.ref(inst)
		return inst

	def __init__(self,filename):
		print "I was constructed using:", filename

Try this code for yourself.

HTH!

Heiko.




More information about the Python-list mailing list