Frozen Flame
Frozen Flame

Reputation: 3245

Descriptor example in Python docs does not work

An example taken from Python docs. Link.

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

But when I do

cell = Cell()
cell.value

exception raised

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

Question: How is the example code expected to be used?

Upvotes: 2

Views: 44

Answers (1)

Josh Smeaton
Josh Smeaton

Reputation: 48720

I think you've found a bug in the documentation. You can't pass (to my knowledge) arguments to getter-type properties. I think the example should be:

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

Upvotes: 2

Related Questions