Is this a closure?

John Machin sjmachin at lexicon.net
Mon Sep 1 02:26:43 CEST 2008


On Sep 1, 9:53 am, ssecorp <circularf... at gmail.com> wrote:
> A method on a class:
>
> def printSelf(self):
>         def printReviews():
>             for review in self.reviews:
>                 review.printSelf()
>         print "Idnbr: ", self.idnumber, "Reviews: ", printReviews()
>

The above appears to be more or less identical in effect to:
def printSelf(self):
    print "Idnbr: ", self.idnumber, "Reviews: "
    for review in self.reviews:
        review.printSelf()
except for spacing and more importantly the second version won't print
the gratuitous None value returned by printReviews().

What are you aiming for? If your purpose is to explore/understand
lexical scopes, I suggest that you get it right in your head in the
context of a simple non-recursive function, then /if necessary/ try to
do it in a recursive class method.

HTH,
John







More information about the Python-list mailing list