To set a static variable within a function

Asked 2 years ago, Updated 2 years ago, 77 views

In C, static was specified in the function like the code below How do I declare static in a function with Python?

void foo()
{
    static int counter = 0;
    counter++;
    printf("counter is %d\n", counter);
}

python static

2022-09-22 22:27

1 Answers

The Python script that does the same thing as the C code you asked is as follows.

def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter
foo.counter = 0

To make foo.counter = 0 above the function, you must create a decoder as follows:

def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate

@static_vars(counter=0)
def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter

def foo():
    try:
        foo.counter += 1
    except AttributeError:
        foo.counter = 1
    finally:
        print("Counter is %d" % foo.counter)



2022-09-22 22:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.