在Python中,函数内部静态变量的等效替代是什么?
在Python中,函数内部静态变量的等效替代是什么?
这段C/C++代码该如何用Python的惯用方式实现?
void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); }
具体来说,如何实现函数级别的静态成员变量,而不是类级别的?将函数放入类中是否会有所改变?
admin 更改状态以发布 2023年5月20日
您可以为函数添加属性,并将其用作静态变量。
def myfunc(): myfunc.counter += 1 print myfunc.counter # attribute must be initialized myfunc.counter = 0
另外,如果您不想在函数外部设置变量,则可以使用 hasattr()
来避免 AttributeError
异常:
def myfunc(): if not hasattr(myfunc, "counter"): myfunc.counter = 0 # it doesn't exist yet, so initialize it myfunc.counter += 1
无论如何,静态变量相当少见,您应该找到一个更好的位置来存储此变量,最可能就是在类内部。
有点顺序颠倒,但这应该是可行的:
def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0
如果您希望计数器初始化代码在顶部而不是底部,请创建一个装饰器:
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
不幸的是,它仍然需要您使用foo。
前缀。
(出处:@ony)