Why doesn't Python have static variables?

后端 未结 9 2436
暗喜
暗喜 2020-11-27 14:48

There is a questions asking how to simulate static variables in python.

Also, on the web one can find many different solutions to create static variables. (Though I

相关标签:
9条回答
  • 2020-11-27 15:39

    For caching or memoization purposes, decorators can be used as an elegant and general solution.

    0 讨论(0)
  • 2020-11-27 15:40

    One alternative to a class is a function attribute:

    def foo(arg):
        if not hasattr(foo, 'cache'):
            foo.cache = get_data_dict()
        return foo.cache[arg]
    

    While a class is probably cleaner, this technique can be useful and is nicer, in my opinion, then a global.

    0 讨论(0)
  • 2020-11-27 15:45

    An ill-advised alternative:

    You can also use the side-effects of the definition time evaluation of function defaults:

    def func(initial=0, my_static=[])
      if not my_static:
        my_static.append(initial)
    
       my_static[0] += 1
      return my_static[0]
    
    print func(0), func(0), func(0)
    

    Its really ugly and easily subverted, but works. Using global would be cleaner than this, imo.

    0 讨论(0)
提交回复
热议问题