[Baypiggies] closures vs. objects
Shannon -jj Behrens
jjinux at gmail.com
Sat Apr 25 09:48:07 CEST 2009
After the meeting, Jon said it would have been good if I showed how
closures compared to objects.
Here's a closure:
def greeter(name):
def greet():
print "Hello,", name
return greet
jj_greeter = greeter('JJ')
jj_greeter()
Here's how to do the same thing, but with an object:
class Greeter:
def __init__(self, name):
self._name = name
def __call__(self):
print "Hello,", self._name
mike_greeter = Greeter('Mike')
mike_greeter()
Perhaps the biggest difference is that with a class, you can have as
many methods as you want (in this class, I just have __call__), but
with a closure, you don't have to explicitly store the name anywhere
(the closure does it for you).
I use a mix of both techniques.
Happy Hacking!
-jj
--
In this life we cannot do great things. We can only do small things
with great love. -- Mother Teresa
http://jjinux.blogspot.com/
More information about the Baypiggies
mailing list