什么是这个C/C++代码的惯用Python等价物?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
Run Code Online (Sandbox Code Playgroud)
具体来说,如何在功能级别实现静态成员,而不是类级别?将函数放入类中会改变什么吗?
当我试图让类装饰器和方法装饰器很好地一起玩时,我遇到了这种行为.从本质上讲,方法装饰器会将某些方法标记为特殊的一些虚拟值,并且类装饰器将在之后出现并稍后填充该值.这是一个简化的例子
>>> class cow:
>>> def moo(self):
>>> print 'mooo'
>>> moo.thing = 10
>>>
>>> cow.moo.thing
10
>>> cow().moo.thing
10
>>> cow.moo.thing = 5
AttributeError: 'instancemethod' object has no attribute 'thing'
>>> cow().moo.thing = 5
AttributeError: 'instancemethod' object has no attribute 'thing'
>>> cow.moo.__func__.thing = 5
>>> cow.moo.thing
5
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么cow.moo.thing = 5不起作用,即使cow.moo.thing很清楚地给我10?为什么cow.moo.__func__.thing = 5有效?我不知道它为什么会这样,但是随机摆弄dir(cow.moo)列表中的东西试图让它起作用突然间,我不明白为什么.