跳过正文
  1. Teches/
  2. 通用编程思想/
  3. 编程概念/

闭包

·347 字·2 分钟
目录

在创建时封装当时状态,并使当时的状态生存周期延长至与闭包生存周期一致
闭包思想产物:
1. python装饰器
2. 回调函数
3. 函数工厂
4. 惰性求值

典型用法
#

1. python装饰器
#

</> python
1def execute(f):
2    f()
3
4@execute
5def execute_when_defined():
6    print('executed')

2. 函数工厂
#

  1. 保存调用函数工厂时的参数
  2. 调用生成的函数时,使用函数工厂创建函数时的参数上下文

示例
#

  1. python api函数工厂
</> python
1def get_table_grids_wp(cli:Client, docid):
2    def func(tableid):
3        return [c['children'][0] for c in cli.fetchblocks(docid, tableid)['data']['items']]
4    return func
5
6get_table_grids = get_table_grids_wp(cli, docid)
7get_table_grids(tid)
  1. go 基础函数工厂
</> go
 1package main
 2
 3import "fmt"
 4
 5// 函数工厂:返回一个加法函数
 6func makeAdder(addend int) func(int) int {
 7    return func(x int) int {
 8        return x + addend
 9    }
10}
11
12func main() {
13    add5 := makeAdder(5)  // 创建一个加5的函数
14    add10 := makeAdder(10) // 创建一个加10的函数
15    
16    fmt.Println(add5(3))   // 输出: 8 (3 + 5)
17    fmt.Println(add10(3))  // 输出: 13 (3 + 10)
18}
  1. go 中间件工厂
  2. 带配置的函数工厂
</> go
 1package main
 2
 3import "fmt"
 4
 5type GreeterConfig struct {
 6    Prefix string
 7    Suffix string
 8}
 9
10// 创建问候函数
11func NewGreeter(config GreeterConfig) func(string) string {
12    return func(name string) string {
13        return fmt.Sprintf("%s, %s%s", config.Prefix, name, config.Suffix)
14    }
15}
16
17func main() {
18    friendlyGreeter := NewGreeter(GreeterConfig{
19        Prefix: "Hello",
20        Suffix: "! Welcome!",
21    })
22    
23    formalGreeter := NewGreeter(GreeterConfig{
24        Prefix: "Dear",
25        Suffix: ", we are pleased to meet you",
26    })
27    
28    fmt.Println(friendlyGreeter("Alice")) // 输出: Hello, Alice! Welcome!
29    fmt.Println(formalGreeter("Bob"))    // 输出: Dear, Bob, we are pleased to meet you
30}
  1. 缓存函数工厂
</> go
 1package main
 2
 3import "fmt"
 4
 5// 创建带缓存的函数
 6func makeCachedFunc(fn func(int) int) func(int) int {
 7    cache := make(map[int]int)
 8    return func(x int) int {
 9        if result, found := cache[x]; found {
10            fmt.Printf("Cache hit for %d\n", x)
11            return result
12        }
13        result := fn(x)
14        cache[x] = result
15        fmt.Printf("Calculated for %d\n", x)
16        return result
17    }
18}
19
20func expensiveCalculation(x int) int {
21    // 模拟耗时计算
22    return x * x
23}
24
25func main() {
26    cachedCalc := makeCachedFunc(expensiveCalculation)
27    
28    fmt.Println(cachedCalc(5)) // 输出: Calculated for 5 \n 25
29    fmt.Println(cachedCalc(5)) // 输出: Cache hit for 5 \n 25
30}