此 C/C++ 代码的惯用 Python 等价物是什么?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
具体来说,如何在函数级别而不是类级别实现静态成员?将函数放入类中会改变什么吗?
原文由 andrewdotnich 发布,翻译遵循 CC BY-SA 4.0 许可协议
此 C/C++ 代码的惯用 Python 等价物是什么?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
具体来说,如何在函数级别而不是类级别实现静态成员?将函数放入类中会改变什么吗?
原文由 andrewdotnich 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以向函数添加属性,并将其用作静态变量。
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
不管怎样,静态变量很少见,你应该为这个变量找到一个更好的地方,很可能是在一个类中。
原文由 vincent 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答5k 阅读✓ 已解决
2 回答1k 阅读✓ 已解决
4 回答937 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
有点颠倒,但这应该有效:
如果你想在顶部而不是底部的计数器初始化代码,你可以创建一个装饰器:
然后使用这样的代码:
不幸的是,它仍然需要您使用
foo.
前缀。(来源: @ony )