Python文档中的描述符示例不起作用

时间:2014-10-23 01:55:03

标签: python

从Python文档中获取的示例。 Link

class Cell(object):
    def getvalue(self, obj):
        "Recalculate cell before returning value"
        self.recalc()
        return obj._value
    value = property(getvalue)

但是当我做的时候

cell = Cell()
cell.value

引发异常

TypeError: getvalue() missing 1 required positional argument: 'obj'

问题: 如何使用示例代码?

1 个答案:

答案 0 :(得分:2)

我认为您在文档中发现了一个错误。你不能传递(据我所知)getter-type属性的参数。我认为这个例子应该是:

class Cell(object):
    def __init__(self, cell):
        self.cell = cell

    def recalc(self):
        self._value = 100 # this wouldn't really return a static value

    def getvalue(self):
        "Recalculate cell before returning value"
        self.recalc()
        return self._value
    value = property(getvalue)

>>> Cell('A1').value
100
相关问题