I'm trying to implement the Borg design pattern found here (recreated below): http://ift.tt/29Ahq4B.
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
def __str__(self): return self.val
I want to run a particular method on the first initialization of this class, but never again. Originally, I tried using some boolean flag, but from my understanding, the Singleton class is initialized multiple times, but the state and behavior are common among all instances. Therefore, any initialization I do within the init method happens more than once, so the flags were reset each time the Singleton method was initialized.
I found a solution that works, but I am wondering what is the most pythonic way to do this, because I don't believe this is it. I did the following:
class Singleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
if not self.__dict__: #I'm just checking that the namespace is empty, knowing it will be filled with something in the future.
firstInitializationMethod()
Any help is much appreciated, and please let me know if more details are needed. I'm new to this. Thanks!
Aucun commentaire:
Enregistrer un commentaire