Why we will use obj$func() often
David MacQuigg
dmq at gain.com
Fri Apr 23 16:01:10 EDT 2004
On Fri, 23 Apr 2004 11:21:16 -0700, "Mark Hahn" <mark at prothon.org>
wrote:
>"David MacQuigg" <dmq at gain.com> wrote
>> Adding syntax or making changes just because it allows you to do
>> something that can't be done in Python is not good. We have to look at
>> *use cases* for these features and compare them to a well-written
>> Python equivalent. Then, we can see if the benefit is worth the extra
>> syntax. We spend far to much time debating syntax without a clear
>> benefit in mind. Show us a nice closure.
>
>The benefits of closures are well known. I'll give you the canonical
>example, but I'm sure textbooks can give you many more (by the way, Python
>cannot do this):
Sorry for my ignorance, oh master. :>)
># tested example
>def getFunc():
> counter = 0
> def count():
> &counter += 1
> print &counter
> return count
>
>c = getFunc()
>c() # prints 1
>c() # prints 2
>c() # prints 3
Here is how I would do it in Python:
class Accumulator:
def __init__(self):
self.count = 0
def bump(self):
self.count += 1
print self.count
c = Accumulator()
c.bump()
c.bump()
c.bump()
It took me a few minutes to understand what the "closure" was doing.
The Python code is more clear ( at least for anyone who will have to
be working with classes anyway). There is nothing new to learn.
Functionality = same
Size of Source Code = same
Transparency = Python wins
-- Dave
P.S. A sincere apology for my gibe above. I couldn't resist. :>)
More information about the Python-list
mailing list