[Tutor] Object defined by initialization parameters ADDITION
Bob Gailer
bgailer at alum.rpi.edu
Mon Apr 24 22:42:21 CEST 2006
Bob Gailer wrote:
> 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
>
>
I neglected to show the function call:
a = makemyObj("a")
b = makemyObj("b")
c = makemyObj("a")
a and c will point to the same object
b will be a different object
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060424/889db232/attachment.html
More information about the Tutor
mailing list