Reputation: 139
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??
Upvotes: 0
Views: 253
Reputation: 5948
That's because you were assigning a value to an attribute of f
, which is global. Any changes you make to a global object's attribute is globally visible (even though in this case your global object is a function and it's not usual to work with attributes in function). When you made your changes, you created a count
variable inside your function's scope, thus not being accessible outside of it.
Upvotes: 1
Reputation: 1704
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
Upvotes: 0