【发布时间】: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