繁体   English   中英

super(Foo,self)和super(Foo,self .__ class__)之间的区别?

[英]Difference between super(Foo, self) and super(Foo, self.__class__)?

我对python非常陌生,所以希望我不缺少太多必要的知识来理解这一点,但......

我有一个具有一些属性的类,我正在尝试覆盖其中一个类似于此示例的setter:

class Foo(object):
    def __init__(self):
        self._x = True

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

class Bar(Foo):
    @property
    def x(self):
        return super().x

    @x.setter
    def x(self, value):
        print('x set')

        super(Bar, self.__class__).x.fset(self, value)

bar = Bar()

# Prints 'x set' as expected:
bar.x = True

这工作正常,但我真的不明白为什么这条线的工作方式...

super(Bar, self.__class__).x.fset(self, value)

......以及它与这条线的区别,它不起作用:

super(Bar, self).x.fset(self, value)

任何指导将不胜感激。

为简化起见,我们假设(如在您的示例中) super总是为Foo定义的内容返回代理,也就是说,不涉及其他类。

  1. 暂时忽略对super的调用,考虑bar.xBar.x之间的区别。 第一个会调用命名属性的getter; 后者只是对房产本身的参考。

  2. 现在考虑一个非属性属性。 super(Bar, self).method将是绑定方法的一个实例,这样super(Bar, self).method(x)将等同于Foo.method(self, x) super(Bar, self.__class__).method ,然而,将是未绑定的方法,即简单的Foo.method

  3. 现在结合步骤1和2.我们知道bar.x将导致调用Bar定义的getter,并且我们知道super(Bar, self)Foo via self的代理。 因此, super(Bar, self).x必须调用不在Bar定义的getter,而在Foo调用。

    我们也知道Bar.x只是对property对象的引用,它不会调用它的getter; 我们知道super(Bar, self.__class__)充当Foo的代理,独立于任何特定对象。 因此,我们可以得出结论,对于Bar的实例selfsuper(Bar, self.__class__).x是对Foo定义的property对象的引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM