ZengJuchen
ZengJuchen

Reputation: 4811

Can I assign attribute to a function inside itself?

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

Answers (2)

chepner
chepner

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

fr1tz
fr1tz

Reputation: 8384

Check out pep-0232. And this question here

Upvotes: 1

Related Questions