[Tutor] Object defined by initialization parameters
Andre Engels
andreengels at gmail.com
Mon Apr 24 16:46:31 CEST 2006
Is it possible to define a class in such a way, that if twice an
object is made with the same initialization parameters, the same
object is returned in both cases?
More specifically, suppose I have the following program:
class myObj(object):
def __init__(self,a):
self._a = a
self._seen = 0
def touch(self):
self._seen += 1
def count(self):
return self._seen
x = myObj("a")
y = myObj("a")
z = myObj("b")
x.touch()
After this, x._seen will return 1, but y._seen and z._seenwill return
0. I would like the definition of the myObj class to be such that
after these definitions x and y refer to the same object, but z to a
different one.
If there is not such possibility, does anyone have a better or more
elegant workaround than the one I am using, which is:
class myObj(object):
def __init__(self,a):
self._a = a
self._seen = 0
def touch(self):
self._seen += 1
def count(self):
return self._seen
def obj(a):
try:
return objects[a]
except KeyError:
objects[a] = myObj(a)
return objects[a]
objects = {}
x = obj("a")
y = obj("a")
z = obj("b")
x.touch()
--
Andre Engels, andreengels at gmail.com
ICQ: 6260644 -- Skype: a_engels
More information about the Tutor
mailing list