Static Variable in Python

The solution, as shown below, is actually quite straight forward. Basically by using Python attribute, you can emulate static variable in a function without using a global variable.
def myfunc():
if not hasattr(myfunc, "counter"):
    myfunc.counter = 0  # it doesn't exist yet, so initialize it
    myfunc.counter += 1

Coming from C-based programming languages, PHP in my case, it going to take a while for me to adapt to Python. Yes, I still code Python like a PHP, hence, more practice needed.

No comments:

Post a Comment