Eleutetio Eleutetio - 1 month ago 24
Python Question

Static function in Python?

I am learning OOP in python and following this tutorial. I am confuse about an example which is shown in this article :

def f(x):
f.counter = getattr(f, "counter", 0) + 1
return "Monty Python"


for i in range(10):
f(i)

print(f.counter)


I have some doubts.

I know what
getattr(f, "counter", 0)
do. Its give optional values of key to dict module. If an attribute name is not in included in either of the dictionary, the attribute name is not defined.

First i thought
f.counter = getattr(f, "counter", 0) + 1
is doing same work as count do so i replaced
f.counter = getattr(f, "counter", 0) + 1
like this:

def f(x):
count=0
count+=x
print(count)

return "Monty Python"


for i in range(10):
f(i)


print(count)


its working fine but last line
print(count)
is giving error. So my confusion is why count is not global but when i used
f.counter = getattr(f, "counter", 0) + 1
then f.counter was global how??

second question is :

Article says


"This can be used as a replacement for the static function variables
of C and C++, which are not possible in Python."


so what is called static function??

Answer

It's important to note that your function creates a variable count every time the function is run, and then once the function exits, count disappears. You could also write the function like this:

def f():
    f.counter = getattr(f, 'counter', 0) + 1

and f.counter would still hold the number of times f had been executed. We can access f.counter because we can access f, and nothing is private in Python. If we try to reference counter by itself outside the function, it will be a NameError, but only because it looks in every namespace it can find and doesn't see anything named counter. You would have to reference f.counter

Comments