My python annoyances so far
Neil Cerutti
horpner at yahoo.com
Thu Apr 26 14:05:45 EDT 2007
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. ;)
>>> def funmaker(f, x):
... return lambda: f(x)
...
>>> d = funmaker(int, 10)
>>> d()
10
In addition, all functions in Python have data members, too.
>>> d.label = "d"
>>> d.label
'd'
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.
> And before someone get's all technical, I know everything in
> Python is an 'object' even None, which implies class, or is it
> the other way around?
Classes are just objects like everything else.
--
Neil Cerutti
Bach's death is attributed to the end of the Baroque era. --Music Lit Essay
More information about the Python-list
mailing list