I want to create a class, and all objects need to have a unique identifier key, and If I attempt to create a new instance of the object with a previously existent key, the instance should be the same as the one that already existing.
Similar to a singleton class, but in this case instead of one class, there are many but different.
My first approach was this
class Master:
existent = {}
def __init__(self, key, value=None):
try:
self = Master.existent[key]
return
except KeyError:
Master.existent[key] = self
# Rest of the __init__ method
But when I compare two objects, something like this A = Master('A', 0) and B = Master('B', 0), the B doesn't share any attributes that It should have, and if the Master class has any _method (single underscore), It also doesn't appear.
Any Idea how could I do this?
I think this is similar to the Factory Methods Pattern, but I'm still having trouble to find the parallels, or how to implemented in an elegant form.
Aucun commentaire:
Enregistrer un commentaire