[Tutor] Object defined by initialization parameters
Bob Gailer
bgailer at alum.rpi.edu
Mon Apr 24 22:17:45 CEST 2006
Andre Engels wrote:
> 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?
>
Use a "factory" function, and store a dictionary of instances as a class
property:
class myObj(object):
instances = {}
def __init__(self,a):
# the rest of your code
def makemyObj(a):
if a in myObj.instances:
return myObj.instances[a]
else:
new_instance = myObj(a)
myObj.instances[a] = new_instance
return new_instance
[snip]
More information about the Tutor
mailing list