代码之家  ›  专栏  ›  技术社区  ›  Tim unnamed eng

假设“obj”具有类型“objtype”,“super(cls,obj)”和“super(cls,objtype)”是否相同?

  •  1
  • Tim unnamed eng  · 技术社区  · 8 年前

    在Python中,假设 obj 具有类型 objtype super(cls,obj) super(cls,objtype) 相同的?

    转换 obj公司 对象类型 哪个在后面 cls 在的MRO中 对象类型 ?

    超级(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 (这不会进一步覆盖 __new__

    super(Singleton, cls) cls公司

    谢谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   snakecharmerb    8 年前

    根据 docs super

    返回一个代理对象,该对象将方法调用委托给类型为的父类或同级类。

    所以 超级的 返回一个对象,该对象知道如何调用类层次结构中其他类的方法。

    超级的 超级的 超级的

    这么说吧 super(SomeClass, cls).some_method() 意味着通话 some_method 课程 SomeClass 超级的 超级的 调用实例方法。

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

    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()
    

    super(C, cls) super() 在python3中已经足够了。

    在你的单身例子中, super(Singleton, cls).__new__(cls) 返回调用的结果 object.__new__(cls) Singleton Singleton.__new__ .