我正在尝试在Python(2.7)中实现Singleton pattern。
我已阅读有关实施的severel帖子(1,2,3,4),我想编写自己的版本。 (我理解的一个版本。我是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)
我在这里滚动:
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
方法?
答案 0 :(得分:0)
问题在于,当您将其插入到类中时,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())