最近我阅读了一篇关于如何在 Python 中制作单例的有趣讨论。其中一个解决方案是一个棘手的装饰器,在其代码中定义一个类作为装饰类的替代品:
def singleton(class_):
class class_w(class_):
_instance = None
def __new__(class2, *args, **kwargs):
if class_w._instance is None:
class_w._instance = super(class_w, class2).__new__(class2, *args, **kwargs)
class_w._instance._sealed = False
return class_w._instance
def __init__(self, *args, **kwargs):
if self._sealed:
return
super(class_w, self).__init__(*args, **kwargs)
self._sealed = True
class_w.__name__ = class_.__name__
return class_w
@singleton
class MyClass(object):
def __init__(self, text):
print text
@classmethod
def name(class_):
print class_.__name__
x = MyClass(111)
x.name()
y = MyClass(222)
print id(x) == id(y)
输出是:
111 # the __init__ is called only on the 1st time
MyClass # the __name__ is preserved
True # this is actually the same instance
据说,如果我们使用super(MyClass, self).__init__(text)
inside __init__
of MyClass
,我们就会进入递归。
我测试了,确实发生了递归。但是,据我所知,MyClass
继承object
,所以super(MyClass, self)
应该只是object
,但事实证明super(MyClass, self)
是__main__.MyClass
您能否逐步解释一下这里发生了什么,以便我了解递归发生的原因?