My question is for validation of my code (any loop holes / bugs) and guidance the best methodology to implement for my requirement.
I am developing a Python application that will have many classes. We need to communicate in between each class - pass data. It would be very clumsy if across all classes I create a setter/getter method and refer them across different classes, hence I prefer to pass a container object in between all of them:
class One
def __init__(self, container):
class Two
def __init__(self, container):
Now obviously I want that this container object should be a Singleton object - only one instance to pass multiple data structures. Below is my code for same [class declaration for Container class]:
import abc
class Container(object):
__metaclass__ = abc.ABCMeta
__data1 = 0
__data2 = 0
@abc.abstractmethod
def dummy():
raise NotImplementedError()
def __init__(self):
self.__data1 = 0
self.__data2 = 1
def SetData(self,value):
self.__data1 = value
def GetData(self):
return self.__data1
class Singleton(Container):
_instances = {}
def __new__(class_, *args, **kwargs):
if class_ not in class_._instances:
class_._instances[class_] = super(Singleton, class_).__new__(class_, *args, **kwargs)
return class_._instances[class_]
def dummy():
pass
Now in my application, I would not be able to create an another separate instance of Container [abstract class] / Singleton class. So I can pass the object of Singleton like as mentioned below:
class One:
def __init__(self, container)
self.value = container.GetData()
................................
container.SetData(9)
Two(container)
class Two:
def __init__(self, container)
self.value = container.GetData()
................................
container.SetData(19)
................................
class Three:
def __init__(self, container)
self.container = Singleton()
................................
container.GetData() # will return value 19 only
container.SetData(19)
................................
if __name__ == "__main__":
container = Singleton()
container.SetData(9)
One(container)
Please comment on my approach and modifications required if any. This code will be pushed in production box - so I want to double check my implementation.