【问题标题】:How to inherit Base class with singleton in python如何在python中用单例继承基类
【发布时间】:2017-02-05 00:15:38
【问题描述】:

我有一个单例基类,我需要在我的另一个类中继承它,但我收到错误消息 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

【问题讨论】:

  • 我认为你提出了一个设计问题......单例意味着哪里只有一个,如果你有一个派生类,你将有多个 (2) 基类实例。你确定你需要一个单例吗?
  • 所以locals() 不起作用?
  • 需要的是ClassOne和ClassTwo都是单例的,classOne有ClassTwo的功能和很少的额外支持,所以我需要使用classOne方法而不是ClassTwo。彻底改变这些是重大变化,因此希望使用继承来实现
  • 我做了这样的更改 @singleton class ClassOne(object): def methodOne(self): print "Method One" def methodTwo(self): print "Method Two" class ClassTwo(ClassOne): pass
  • @santosh edit 问题,代码在 cmets 中不可读。我还建议您添加一些 prints 以更好地理解代码中的控制流。

标签: python python-2.7


【解决方案1】:

您必须将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 类都是单例类

注意,从单例类继承是不常见的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 2011-10-26
    • 2019-01-06
    • 1970-01-01
    • 2012-05-11
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多