在TypeError中实现Singleton模式结果:必须使用Singleton实例作为第一个参数调用未绑定方法foobar()

时间:2015-07-30 13:47:00

标签: python python-2.7 design-patterns singleton

我正在尝试在Python(2.7)中实现Singleton pattern

我已阅读有关实施的severel帖子(1234),我想编写自己的版本。 (我理解的一个版本。我是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方法?

1 个答案:

答案 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())