闭包:一个包含有环境变量取值的函数对象。环境变量取值被保存在函数对象的__closure__属性中。
示例:
def line_conf(a, b):
def line(x):
return ax + b
return line
line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
print(line1(5), line2(5))
这个例子中,函数line与环境变量a,b构成闭包。在创建闭包的时候,我们通过line_conf 的参数a,b说明了这两个环境变量的取值,这样,我们就确定了函数的最终形式(y = x + 1和y = 4x + 5)。我们只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,闭包也具有提高代码可复用性的作用。
装饰器可以对一个函数方法或进行加工。
修饰函数:
def decorator(F):
def new_F(a, b):
print("input", a, b)
return F(a, b)
return new_F
# get square sum
@decorator
def square_sum(a, b):
return a**2 + b**2
# get square diff
@decorator
def square_diff(a, b):
return a**2 - b**2
print(square_sum(3, 4))
print(square_diff(3, 4))
该语法将要装饰的函数作为decorator的参数,在其中定义新函数,添加功能并将其最为对象返回。
@decorator相当与如下代码:
square_sum = decorator(square_sum)
square_sum(3, 4)
装饰类:
def decorator(aClass):
class newClass:
def __init__(self, age):
self.total_display = 0
self.wrapped = aClass(age)
def display(self):
self.total_display += 1
print("total display", self.total_display)
self.wrapped.display()
return newClass
@decorator
class Bird:
def __init__(self, age):
self.age = age
def display(self):
print("My age is",self.age)
eagleLord = Bird(5)
for i in range(3):
eagleLord.display()
该语法将要装饰的类作为decorator的参数,在其中定义新类,添加功能并将其最为新类返回。