假设 `obj` 的类型为 `objtype`,那么 `super(cls,obj)` 和 `super(cls,objtype)` 是否相同?

Assuming `obj` has type `objtype`, are `super(cls,obj)` and `super(cls,objtype)` the same?

在Python中,假设obj的类型是objtypesuper(cls,obj)super(cls,objtype)是一样的吗?

super(cls,obj)obj 转换为另一个对象是否正确,其 class 是 objtype 的超 class,在 [=18= 之后] 在 objtype?

的 MRO 中

super(cls,objtype)是什么意思?


例如,给定单例设计模式的实现:

class Singleton(object):
    _singletons = {}
    def __new__(cls, *args, **kwds):
        if cls not in cls._singletons:
            cls._singletons[cls] = super(Singleton, cls).__new__(cls)
        return cls._singletons[cls]

Singleton 的任何子class(不会进一步覆盖 __new__)只有一个实例。

super(Singleton, cls) 是什么意思,其中 cls 是 class?它是什么 return?

谢谢。

根据 docssuper

Return a proxy object that delegates method calls to a parent or sibling class of type.

所以 super returns 一个知道如何调用 class 层次结构中其他 class 方法的对象。

super的第二个参数是super绑定的对象;通常这是 class 的一个实例,但是如果 super 在 class 方法或静态方法的上下文中被调用,那么我们想在 super 上调用方法=49=] 对象本身而不是一个实例。

所以调用 super(SomeClass, cls).some_method() 意味着在 classes 上调用 some_method SomeClass 的后裔,而不是 这些 class 的实例 。否则 super 调用的行为就像实例方法中的 super 调用一样。

使用不太复杂的代码看起来更自然:

class C(SomeBaseClass):

    def method(self):
        # bind super to 'self'
        super(C, self).method()

    @classmethod
    def cmethod(cls):
        # no 'self' here -- bind to cls
        super(C, cls).cmethod()

请注意python2中需要super(C, cls),但python3中空super()即可。

在您的单例示例中,super(Singleton, cls).__new__(cls) returns 调用 object.__new__(cls) 的结果,Singleton 的一个实例。以这种方式创建它是为了避免递归调用 Singleton.__new__.