I have a singleton implemented like this:
class Test123(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Test123, cls).__new__(cls, *args, **kwargs)
return cls._instance
def initialize(self):
self.attr1 = 500
self.attr2= 0
self.attr3= 0.10
def printit(self):
print self.attr1
print self.attr2
print self.attr3
I don;t implement __init__ because it is called every time I use the singleton, so to get around it, I simply call initialize at the start of my script.
Whenever i run it:
Test123().initialize()
time.sleep(1)
Test123().printit()
I get this error:
Traceback (most recent call last):
File "Z:\test\test123.py", line 22, in <module>
500
Test123().printit()
File "Z:\test\test123.py", line 17, in printit
print self.attr2
AttributeError: 'Test123' object has no attribute 'attr2'
Any ideas what is going on? I am using another singleton and it's not doing this. Plus, attr1 gets printed fine, I very confused. Might it have something to do with naming, maybe some other singleton has an attribute named attr2?
EDIT: the testcase seems to work fine after I changed repo, so here is the actual code
import MySQLdb
class DataAccessLayer():
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(DataAccessLayer, cls).__new__(cls, *args, **kwargs)
return cls._instance
def initialize(self):
#init local connection
self.dalConnection = 0
try:
self.dalConnection = MySQLdb.connect('localhost', 'root', 'awesomepassword', 'arb');
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
def __del__(self):
self.dalConnection.close()
def addrow(self):
try:
cur = self.dalConnection.cursor()
cur.close()
self.dalConnection.commit()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
DataAccessLayer().initialize()
DataAccessLayer().addrow()
Creates this error:
Traceback (most recent call last):
File "Z:\test\DataAccess.py", line 36, in <module>
DataAccessLayer().addrow()
File "Z:\test\DataAccess.py", line 25, in addOption
cur = self.dalConnection.cursor()
AttributeError: DataAccessLayer instance has no attribute 'dalConnection'
Exception AttributeError: "DataAccessLayer instance has no attribute 'dalConnection'" in <bound method DataAccessLayer.__del__ of <__main__.DataAccessLayer instance at 0x00000000022A2748>> ignored