2012-03-24 135 views
2

我已經實現了這樣一個單: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 
+2

適用於我。你是否也經歷過測試用例的失敗,或者僅僅是在真正的程序中?什麼Python版本? – doublep 2012-03-24 21:12:36

+0

nvm,剛剛再次嘗試了測試用例,似乎工作正常(我從不同的回購中啓動它)。 – 2012-03-24 21:19:46

+0

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

回答

2

DataAccessLayer是一箇舊式類。嘗試class DataAccessLayer(object): ...

更新:

Class Types

Class types, or 「new-style classes,」 are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override __new__(). The arguments of the call are passed to __new__() and, in the typical case, to __init__() to initialize the new instance.

Classic Classes

Class objects are described below. When a class object is called, a new class instance (also described below) is created and returned. This implies a call to the class’s __init__() method if it has one. Any arguments are passed on to the __init__() method. If there is no __init__() method, the class must be called without arguments.

來源:the python reference

+0

它工作thx :)其真棒和所有,但任何進一步的解釋? – 2012-03-24 21:35:26

+0

Google「舊式課程」。 – katrielalex 2012-03-24 21:56:01

0

稍微偏離主題,但...這似乎Python的我根本不會。我會嘗試寫一個裝飾類單身,所以我可以做

@Sigleton 
class MySingleton(object): 
    pass 

您也可以重複使用,如果很快,如果你再次需要它的時候......

注:它可以使小的元數據混亂(MySingleton是Singleton的實例,而不是MySingleton),但也許functools.wraps可以幫助某種方式...