A critic of Guido's blog on Python's lambda
David C. Ullrich
ullrich at math.okstate.edu
Mon May 8 10:00:13 EDT 2006
On Mon, 08 May 2006 08:05:38 -0500, David C. Ullrich
<ullrich at math.okstate.edu> wrote:
>[...]
>
>def acall(cell, value):
> cell.owner.slots['b'].value = value + 1
Needing to say that sort of thing every time
you define a callback isn't very nice.
New and improved version:
"""PyCells.py"""
class Cell:
def __init__(self, name, owner, callback):
self.name = name
self.callback = callback
self.owner = owner
def onchange(self, value):
self.value = value
self.callback(self, value)
def __setitem__(self, name, value):
self.owner.slots[name].value = value
class Cells:
def __init__(self):
self.__dict__['slots'] = {}
def __setattr__(self, name, value):
self.slots[name].onchange(value)
def __getattr__(self, name):
return self.slots[name].value
def AddCell(self, name, callback):
self.slots[name] = Cell(name, self, callback)
Sample:
cells = Cells()
def acall(cell, value):
cell['b'] = value + 1
cells.AddCell('a',acall)
def bcall(cell, value):
cell['a'] = value - 1
cells.AddCell('b',bcall)
cells.a = 42
print cells.a, cells.b
cells.b = 24
print cells.a, cells.b
#OR you could give Cell a __setattr__ so the above
#would be cell.a = value - 1. I think I like this
#version better; in applications I have in mind I
#might be iterating over lists of cell names.
************************
David C. Ullrich
More information about the Python-list
mailing list