Python中的闭包

时间:2023-03-08 16:48:15

简单的闭包的栗子:

def counter(statr_at = 0):
count = 1
def incr():
nonlocal count #注意由于count类型为immutable,所以需要声明清楚在此局部作用域内引用的是外部作用域那个count
count += 1
return count
return incr
>>> count = counter(4)
>>> count()
2
>>> count()
3
>>> count()
4
>>> count()
5
>>> count()
6
>>> count()
7
>>> count()
8
>>> count()
9
>>> count()
10
>>> count()
11

这种行为可用C++11模拟如下:

#include<iostream>
#include<memory>
using namespace std;
class Count{
public:
Count(const shared_ptr<int>& p) :sp(p){}
int operator()(){
(*sp)++;
return (*sp);
}
private:
shared_ptr<int> sp;
};
Count func(int k){
shared_ptr<int> sp = make_shared<int>(k);
return Count(sp);
}
int main(){
auto c = func(10);
cout << c() << endl;
cout << c() << endl;
cout << c() << endl;
return 0;
}