python闭包的功能是什么

本篇内容主要讲解“python闭包的功能是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python闭包的功能是什么”吧!

说明

1、闭包可以避免使用全局变量,并提供某种形式的变量私有,即提供面向对象的解决方案。

2、当一个类中需要实现的方法很少时,闭包可以提供另一种实现封装的方法和更优雅的解决方案。但是,如果属性和方法的数量增加,最好实现一个类。

实例

def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier
 
 
# Multiplier of 3
times3 = make_multiplier_of(3)
 
# Multiplier of 5
times5 = make_multiplier_of(5)
 
# Output: 27
print(times3(9))
 
# Output: 15
print(times5(3))
 
# Output: 30
print(times5(times3(2)))

到此,相信大家对“python闭包的功能是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!