[英]How to inherit Base class with singleton in python
我有单例的基类,我需要在我的另一个类中继承它,但我收到错误消息 TypeError: Error when call the metaclass bases function() argument 1 must be code, not 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
A
类和B
类都是单例
请注意,从单例类继承并不常见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.