python - 如何在Python中使用单例继承基类

标签 python python-2.7

我有一个单例基类,我需要在另一个类中继承它,但我收到错误消息: TypeError:调用元类基时出错 function() 参数 1 必须是代码,而不是 str

有人可以帮忙解决这个问题吗? 下面是示例代码。

def singleton(cls):
  instances = {}
  def getinstance():
    if cls not in instances:
      instances[cls] = cls()
    return instances[cls]
  return getinstance

@singleton
class ClassOne(object):

  def methodOne(self):
    print "Method One"

  def methodTwo(self):
    print "Method Two"


class ClassTwo(ClassOne):
  pass

最佳答案

您必须将singleton 设为类而不是函数才能使派生工作正常进行。下面是一个在 Python 2.7 和 3.5 上都经过测试的示例:

class singleton(object):
    instances = {}
    def __new__(cls, clz = None):
        if clz is None:
            # print ("Creating object for", cls)
            if not cls.__name__ in singleton.instances:
                singleton.instances[cls.__name__] = \
                    object.__new__(cls)
            return singleton.instances[cls.__name__]
        # print (cls.__name__, "creating", clz.__name__)
        singleton.instances[clz.__name__] = clz()
        singleton.first = clz
        return type(clz.__name__, (singleton,), dict(clz.__dict__))

如果您将其与示例类一起使用:

@singleton
class ClassOne(object):

  def methodOne(self):
    print "Method One"

  def methodTwo(self):
    print "Method Two"


class ClassTwo(ClassOne):
  pass

AB都将是单例

请注意,从单例类继承的情况并不常见。

关于python - 如何在Python中使用单例继承基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39723398/

相关文章:

python - 只能使用关联表对象定义二级关系,不能使用名称

python - 根据规则对python中的列表进行排序

python - 使用 Python 在 JIRA 中使用受让人、观察者和附件创建新问题

python - GTK 焦点链

python - 如何在 Flask 上返回 400(错误请求)?

python 无法识别我的函数

python - 使用 Pandas 如何计算数据组?

Django Rest Framework 模型序列化器没有唯一的共同验证

python - 将 python 更改为/usr/local/bin/python?

python - 通过指向该函数的指针获取函数参数值?