Reputation: 4811
Today I found that I can assign attribute to function, but when I tried to assign the attribute inside itself, I failed:
>>> def a():
... pass
...
>>> a.x = 1
>>> a.x
1
>>> def b():
... b.x = 2
...
>>> b.x
AttributeError: 'function' object has no attribute 'x'
Is there a way to assign attribute to a function inside himself?
If there isn't, what's the usage of a function's attribute?
Upvotes: 0
Views: 93
Reputation: 531345
The body of a function is not evaluated until the function is actually called; b.x
in your example does not exist until b
has been called at least once.
One use is to simulate C-style static variables, whose values persist between calls to the function. A trivial example counts how many times the function has been called.
def f():
f.count += 1
print "Call number {0}".format(count)
f.count = 0
Note that there is no problem assigning to f.count
from inside count
, but the initial assignment must occur after f
is defined, since f
does not exist until then.
Upvotes: 2