In programming languages, closures (also lexical closures or function closures) are a technique for implementing lexically scoped name binding in languages with first-class functions.
解释:
在编程语言中,闭包(也词法闭包或函数闭包)是结合拥有 First-class function 的语言,实现词法作用域名的一种技术。
根据类型的值的可赋值状况,可以把类型分为三类
下面我们举一个例子来展示如何使用闭包代替类。
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
class Multiplier(object):
def __init__(self, faciend):
self.faciend = faciend
def product(self, multiplicator):
return self.faciend * multiplicator
if __name__ == "__main__":
# 使用闭包
# 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: 27
mul = Multiplier(3)
print(mul.product(9))
# Output: 15
mul = Multiplier(5)
print(mul.product(3))
本文地址已经归档到github,您可以访问下面的链接获得。
代码地址
如果觉得本文对您有帮助,敬请点赞。