Is this a closure?

S

ssecorp

A method on a class:

def printSelf(self):
def printReviews():
for review in self.reviews:
review.printSelf()
print "Idnbr: ", self.idnumber, "Reviews: ", printReviews()

I don't have to pass an argument to printReviews because everything
defined inside printSelf is aware of outer variables? Or is that
wrong? If it is right, is this what a closure means?

Because Python is lexically scoped right? Is lexical scope+closures =
organized dynamic scope kind of if you get my point?
 
C

Chris Rebert

Yes, printReviews() is a closure. In particular, it's closing over the
variable "self", which it's getting lexically from printSelf().
- Chris
 
J

John Machin

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top