我已經實現了這樣一個單:Python的單屬性錯誤
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
我不;噸實現__init__,因爲它叫我每次使用Singleton時間,所以要解決它,我只需調用初始化在我的腳本的開始。
每當我運行它:
Test123().initialize()
time.sleep(1)
Test123().printit()
我得到這個錯誤:
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'
任何想法是怎麼回事?我正在使用另一個單身人士,並沒有這樣做。另外,attr1打印得很好,我很困惑。可能它與命名有關,也許其他單例有一個名爲attr2的屬性?
編輯:測試用例看來以後我改回購做工精細,所以這裏是實際的代碼
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()
創建此錯誤:
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
適用於我。你是否也經歷過測試用例的失敗,或者僅僅是在真正的程序中?什麼Python版本? – doublep 2012-03-24 21:12:36
nvm,剛剛再次嘗試了測試用例,似乎工作正常(我從不同的回購中啓動它)。 – 2012-03-24 21:19:46
Python有一個名爲[Borg]的設計模式(http://stackoverflow.com/questions/1318406/why- is-the-borg-pattern-python-only-singleton-pattern-in-python),它通常被認爲比單身更加整潔。 – katrielalex 2012-03-24 21:59:03