Home > python > static variables

static variables

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?

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 Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: