Python offers the possibility to store attributes on a function. This can be very useful in a number of situations. Below an example that shows usage.
import inspect
def viewCount(page):
#returns a function which keeps track of how many times the page got viewed
def f():
f.numberOfViews += 1
return f.numberOfViews
f.__name__ = "ViewCount for page " + page
f.numberOfViews = 0
return f
viewCountOne = viewCount('index.html')
viewCountTwo = viewCount('faq.html')
print viewCountOne()
print viewCountOne()
print viewCountTwo()
print viewCountOne()
print viewCountTwo()
print viewCountOne.__name__
print viewCountTwo.__name__
print hasattr(viewCountOne, 'numberOfViews')
print inspect.isfunction(viewCountOne)
print viewCountOne.__name__.find('index') != -1
1
2
1
3
2
ViewCount for page index.html
ViewCount for page faq.html
True
True
True
Nah, I think it's not quite readable. It's kinda reduced analogue of class/object. I'd better create ViewCounter class with appropriate methods and fields.
ReplyDeleteBut nice to know this feature.
Well.. some experts in Python would argue about overusing classes. It's the one thing OO programmers always easily fallback to introducing unnecessary noise. In fact I read that they tried to eliminate as many possible classes in standard Python as possible. And besides that, I think the above approach is almost identical to programming in Javascript where a function can also have attributes.
ReplyDelete