handler.py
class handler:
cursor = None
_instance= None
db = MySQLdb.connect("localhost","root","root","db" )
count=0
@staticmethod
def getInstance():
if(handler._instance == None):
handler._instance = handler()
print "new"
return handler._instance
def __init__(self):
handler.cursor = handler.db.cursor()
print "ok"
obj1 = handler.getInstance()
obj2 = handler.getInstance() # both objects correpond to same single instance of class 'handler'.
If you call getInstance() function in two different files simultaneously to create object in each of them..it creates separate single instances. But I want the same single instance to be used in each of them so that any changes made by one program to that instance gets reflected in other program running simultaneously. For Example:
test1.py
import handler
import time
x = handler.handler.getInstance()
time.sleep(20)
test2.py
import handler
y = handler.handler.getInstance()
When I execute both files simultaneously, 'print "new"' statement gets executed twice, but I want it to be executed only once to ensure that only a single instance of class 'handler' gets created.
Relevant References (this is in Java and I tried to do in python....didn't work):
Creating one instance of an object and using the same instance in different class files