闭包:(返回函数的行为叫闭包??)
#函数也是对象,所以可以被传递
def line_conf(a,b):
def line(x):
return a*x+b
return line line1=line_conf(1,1)
line2=line_conf(4,5)
print(line1,line2) #闭包:包含有环境变量取值的函数对象
#函数line与环境变量a,b构成闭包
#通过闭包,得到直线表达函数 y=x+1 y=4x+5
<function line_conf.<locals>.line at 0x00000000026FA9D8> <function line_conf.<locals>.line at 0x00000000026FAB70>
@修饰符(装饰器):
函数可以赋值给变量,变量可以调用函数:
def now():
print("2017-12-21")
f=now
print(f)
f()
<function now at 0x00000000020FCBF8>
2017-12-21
如果要增强now函数的功能,但不改变now函数的定义,可以在程序执行的时候,通过装饰器给函数增强功能。这种方法叫做:装饰器(Decorator)。
比如,新增的功能是打印
作为装饰器的打印函数,本质上是个返回函数的高阶函数:
def log(func):
def wrapper(*args,**kw):
print('call %s():' % func.__name__)
return func(*args,**kw)
return wrapper @log
def now():
print("2017-12-21") now()
call now():
2017-12-21
def makebold(fn):
def wrapped():
return "<b>"+fn()+"</b>"
return wrapped def makeitalic(fn):
def wrapped():
return "<i>" +fn()+"</i>"
return wrapped @makebold
@makeitalic
def hello():
return "hello world" print(hello())
<b><i>hello world</i></b>
#带参数的装饰器 def makebold(pre=""):
def printMakeBold(fn):
def wrapped():
print(pre)
return "<b>"+fn()+"</b>"
return wrapped
return printMakeBold @makebold("测试")
def printfn():
return "helloworld" print(printfn())
测试
<b>helloworld</b>
#装饰器用于类 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)
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中,我们返回了一个新类newClass。在新类中,我们记录了原来类生成的对象(self.wrapped),并附加了新的属性total_display,用于记录调用display的次数。我们也同时更改了display方法。
#
#
# 通过修改,我们的Bird类可以显示调用display的次数了。
total display 1
total display 2
total display 3