Archive
Posts Tagged ‘static variable’
static variables
June 25, 2013
Leave a comment
Problem
In C, you can use static variables in a function. These variables are initialized once and then they keep their values between function calls. How to do the same in Python?
Solution
Here is an example:
def name_generator():
if not hasattr(name_generator, "cnt"):
name_generator.cnt = 0 # it doesn't exist yet, so initialize it
#
result = "name-{cnt}".format(cnt=name_generator.cnt)
name_generator.cnt += 1
return result
for _ in range(3):
print name_generator()
# name-0
# name-1
# name-2
Categories: python
static variable
