Reputation: 902
source: Learning python by mark lutz
area of content:page #503
classes versus closures: It states that " classes may seem better at state retention because they make their memory more explicit with attribute assignments.
closure functions often provide a lighter-weight and viable alternative when retaining state is the only goal. They provide for per-call localized storage for data required by a single nested function.
What does state-rentention mean and how does it make memory more explicit with attribute assignments?
could anyone provide an example which proves more lighter-weight for closure in the case of retaining state and explain what per-localized storage for data mean in the context of single nested function ?
Upvotes: 3
Views: 772
Reputation: 30151
This is a simple closure:
def make_counter(start=0):
count = start - 1
def counter():
nonlocal count # requires 3.x
count += 1
return count
return counter
You call it like this:
>>> counter = make_counter()
>>> counter()
0
>>> counter()
1
>>> # and so on...
As you can see, it keeps track of how many times it's been called. This information is called "state." It is "per-call localized state" because you can make several counters at once, and they will not interfere with each other. In this case, the state is retained (almost) implicitly, based on the closure keeping a reference to the count
variable from its enclosing scope. On the other hand, a class would be more explicit:
class Counter:
def __init__(self, start=0):
self.count = start - 1
def __call__(self):
self.count += 1
return self.count
Here, the state is explicitly attached to the object.
Upvotes: 6