Python: static variable decorator

前端 未结 8 697

I\'d like to create a decorator like below, but I can\'t seem to think of an implementation that works. I\'m starting to think it\'s not possible, but thought I would ask yo

8条回答
  •  伪装坚强ぢ
    2021-01-06 16:13

    How about this, without decorators?

    class State(dict):
        """Object interface to dict."""
        def __getattr__(self, name):
            try:
                return self[name]
            except KeyError:
                raise AttributeError, name
    
    def f(d=State(x=0)):
        d.x += 1
        return d.x
    

    And here is it in action:

    >>> f()
    1
    >>> f()
    2
    >>> f()
    3
    

提交回复
热议问题