My python annoyances so far
Jean-Paul Calderone
exarkun at divmod.com
Thu Apr 26 14:22:28 EDT 2007
On 26 Apr 2007 20:05:45 +0200, Neil Cerutti <horpner at yahoo.com> wrote:
>On 2007-04-26, Steven Howe <howe.steven at gmail.com> wrote:
>> flifus at gmail.com wrote:
>>>> Well, why do some things in the library have to be functions,
>>>> and other things have to be class methods?
>>
>> Perhaps because some things are more naturally function like?
>> For 'instance' (pardon the pun), functions shouldn't retain
>> data. They perform an operation, return data and quit. While
>> retaining data is a feature of an class/instance.
>
>Functions do retain data. Classes and instances are just a
>convenient notation. ;)
>
> [snip]
>
>Python's scoping rules make certain kinds of functional idioms
>hard to use, though. I'm not sure how to get the following to
>work in Python using functions:
>
>>>> def account(s):
>... b = s
>... def add(a):
>... b += a
>... def balance():
>... return b
>... return add, balance
>...
>>>> add, balance = account(100)
>>>> balance()
>100
>>>> add(5)
>Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 4, in add
>UnboundLocalError: local variable 'b' referenced before assignment
>
>Anyhow, it doesn't work, but you can see how closely it resembles
>a class definition.
Use the outfix closure operator, []:
>>> def account(s):
... b = [s]
... def add(a):
... b[0] += a
... def balance():
... return b[0]
... return add, balance
...
>>> add, balance = account(100)
>>> add(5)
>>> balance()
105
>>>
;)
Jean-Paul
More information about the Python-list
mailing list