What is the Python equivalent of static variables inside a function?

前端 未结 26 2799
天命终不由人
天命终不由人 2020-11-22 00:45

What is the idiomatic Python equivalent of this C/C++ code?

void foo()
{
    static int counter = 0;
    counter++;
          


        
26条回答
  •  太阳男子
    2020-11-22 01:26

    A bit reversed, but this should work:

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

    If you want the counter initialization code at the top instead of the bottom, you can create a decorator:

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

    Then use the code like this:

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

    It'll still require you to use the foo. prefix, unfortunately.

    (Credit: @ony)

提交回复
热议问题