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??
countisn't defined in a global scope, only the scope off. You can't access it outside off. Side note: function attributes are almost never used, and I would question any tutorial that recommends them.