请考虑以下简单示例类,该类具有在调用时公开某些内部数据的修改版本的属性:
class Foo(object):
def __init__(self, value, offset=0):
self._value = value
self.offset = offset
@property
def value(self):
return self._value + self.offset
@value.setter
def value(self, value):
self._value = value
这些value.setter工作适用于常规任务,但当然会因复合分配而中断:
>>> x = Foo(3, 2) >>> x.value 5 >>> x.value = 2 >>> x.value 4 >>> x.value += 5 >>> x.value 11
期望的行为x.value += 5应该等同于x.value = x._value + 5,而不是x.value = x.value + 5.有没有办法实现这个(使用属性接口)纯粹在Foo类中?
| 归档时间: |
|
| 查看次数: |
420 次 |
| 最近记录: |