Tag: 描述符

如果在派生类中覆盖此属性,如何调用基类的属性?

我正在把我的一些阶级从吸收者和制定者的广泛使用改变为对属性更为pythonic的使用。 但是现在我被卡住了,因为我之前的一些getter或setter会调用基类的相应方法,然后执行其他的操作。 但是,怎样才能完成属性? 如何在父类中调用属性getter或setter? 当然,调用属性本身会给出无限recursion。 class Foo(object): @property def bar(self): return 5 @bar.setter def bar(self, a): print a class FooBar(Foo): @property def bar(self): # return the same value # as in the base class return self.bar # –> recursion! @bar.setter def bar(self, c): # perform the same action # as in the base class self.bar […]

了解__get__和__set__以及Python描述符

我想了解Python的描述符是什么,以及它们可以用于什么。 但是,我没有做到这一点。 我明白他们是如何工作的,但这是我的疑惑。 考虑下面的代码: class Celsius(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value) class Temperature(object): celsius = Celsius() 为什么我需要描述符类? 请用这个例子或者你认为更好的例子来解释。 什么是instance和owner ? (在__get__ )。 所以我的问题是,这里的第三个参数的目的是什么? 我将如何调用/使用这个例子?