2012-03-24 108 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可以帮助某种方式...