简单单例实现中的super(type,subclass)

2024-06-17 18:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在python中实现naivesingleton时,我遇到了一个超级关键字的问题。像往常一样,超人的行为总是很狡猾和有缺陷的,希望有人能对此有所启示。谢谢:)

问题是:

class Singleton(object):
    def __new__(cls,*args,**kw):
        if not hasattr(cls,'_instance'):
            #create a instance of type cls,
            origin=super(Singleton,Singleton).__new__(cls,*args,**kw)
            cls._instance=origin
        return cls._instance

class B(Singleton):
    def __init__(self,b):
        self.b=b

它确实有效,但我想知道

如果我把第5行改成下面的行会更好吗,就像大多数书中那样?在

^{pr2}$

有什么区别?在


Tags: instanceselfnewifobjectdefargs关键字
1条回答
网友
1楼 · 发布于 2024-06-17 18:26:54

super()在当前对象的MRO中搜索下一个具有所请求属性的类。super()的第一个参数确定MRO搜索的起点,第二个参数确定从中获取MRO的对象。在

只要不使用多重继承,MRO就很简单。^在这种情况下,{}将始终位于MRO中的同一位置。对于多重继承,子类的MRO中出现Singleton的位置会有所不同,您确实希望使用cls来获得当前的MRO,而不是仅仅是Singleton的MRO。在

对于您的简单示例,忽略cls(例如B)是可以的:

>>> class Singleton(object):
...     def __new__(cls,*args,**kw):
...         if not hasattr(cls,'_instance'):
...             #create a instance of type cls,
...             origin=super(Singleton,Singleton).__new__(cls,*args,**kw)
...             cls._instance=origin
...         return cls._instance
... 
>>> class B(Singleton):
...     def __init__(self,b):
...         self.b=b
... 
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.Singleton'>, <type 'object'>)
>>> Singleton.__mro__
(<class '__main__.Singleton'>, <type 'object'>)

因此super(Singleton, Singleton)和{}最终在同一个子列表中搜索,只找到object。在

但是,使用多重继承,您将得到一个非常不同的MRO;请注意,Foo列在Singleton和{}之间:

^{pr2}$

如果使用super(Singleton, Singleton),那么在查找继承方法时,Foo将被无意中跳过。super(Singleton, cls)将搜索(Foo, object)super(Singleton, Singleton)将只查看object。在

相关问题 更多 >