我正在尝试在Python(2.7)中实现Singleton模式。
我读了几个关于实现的帖子(1,2,3,4),我想编写我自己的版本。一个我能理解的版本。I'm new to Python.)
所以我用一个方法创建了一个单例,这个方法将创建我的单个对象,它将在每次Singleton.Instance()
调用时返回。
但是错误信息总是一样的:
Traceback (most recent call last):
File "./test4.py", line 24, in <module>
print id(s.Instance())
File "./test4.py", line 15, in Instance
Singleton._instance = Singleton._creator();
TypeError: unbound method foobar() must be called with Singleton instance as first argument (got nothing instead)
Here I roll:
class Singleton(object):
_creator = None
_instance = None
def __init__(self, creator):
if Singleton._creator is None and creator is not None:
Singleton._creator = creator
def Instance(self):
if Singleton._instance is not None:
return Singleton._instance
Singleton._instance = Singleton._creator();
return Singleton._instance;
def foobar():
return "foobar"
s = Singleton( foobar )
print id(s.Instance())
为什么?更具体地说:我如何在Python中调用存储在类变量中的def
方法?
问题是当你把它插入到类中时,Python会自动把它变成一个方法。您需要使它成为一个静态方法来避免这种情况。
class Singleton(object):
_creator = None
_instance = None
def __init__(self, creator):
if Singleton._creator is None and creator is not None:
Singleton._creator = staticmethod(creator)
def Instance(self):
if Singleton._instance is not None:
return Singleton._instance
Singleton._instance = Singleton._creator();
return Singleton._instance;
def foobar():
return "foobar"
s = Singleton( foobar )
print id(s.Instance())