My python annoyances so far

Paul McGuire ptmcg at austin.rr.com
Thu Apr 26 17:48:07 EDT 2007


On Apr 26, 1:22 pm, Jean-Paul Calderone <exar... at divmod.com> wrote:
> On 26 Apr 2007 20:05:45 +0200, Neil Cerutti <horp... at yahoo.com> wrote:
>
>
>
>
>
> >On 2007-04-26, Steven Howe <howe.ste... at gmail.com> wrote:
> >> fli... 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- Hide quoted text -
>
> - Show quoted text -

Check out the Percent class I posted at
http://www.programmingforums.org/forum/f43-python/t12461-arithmetic-by-percentage.html#post123290.
It allows you to write code like:

discount = Percent(20)
origprice = 35.00
saleprice = origprice - discount

-- Paul





More information about the Python-list mailing list