![](/img/trans.png)
[英]why is there difference between calling super().foo and super().__getattribute__("foo")
[英]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
定义的内容返回代理,也就是说,不涉及其他类。
暂时忽略对super
的调用,考虑bar.x
和Bar.x
之间的区别。 第一个会调用命名属性的getter; 后者只是对房产本身的参考。
现在考虑一个非属性属性。 super(Bar, self).method
将是绑定方法的一个实例,这样super(Bar, self).method(x)
将等同于Foo.method(self, x)
。 super(Bar, self.__class__).method
,然而,将是未绑定的方法,即简单的Foo.method
。
现在结合步骤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
的实例self
, super(Bar, self.__class__).x
是对Foo
定义的property
对象的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.