python 修饰符和装饰器_【python】闭包、@修饰符(装饰器)、

闭包:(返回函数的行为叫闭包??)

1 #函数也是对象,所以可以被传递

2 defline_conf(a,b):3 defline(x):4 return a*x+b5 returnline6

7 line1=line_conf(1,1)8 line2=line_conf(4,5)9 print(line1,line2)10

11 #闭包:包含有环境变量取值的函数对象

12 #函数line与环境变量a,b构成闭包

13 #通过闭包,得到直线表达函数 y=x+1 y=4x+5

.line at 0x00000000026FA9D8> .line at 0x00000000026FAB70>

@修饰符(装饰器):

函数可以赋值给变量,变量可以调用函数:

defnow():print("2017-12-21")

f=nowprint(f)

f()

2017-12-21

如果要增强now函数的功能,但不改变now函数的定义,可以在程序执行的时候,通过装饰器给函数增强功能。这种方法叫做:装饰器(Decorator)。

比如,新增的功能是打印

作为装饰器的打印函数,本质上是个返回函数的高阶函数:

deflog(func):def wrapper(*args,**kw):print('call %s():' % func.__name__)return func(*args,**kw)returnwrapper

@logdefnow():print("2017-12-21")

now()

call now():

2017-12-21

1 defmakebold(fn):2 defwrapped():3 return ""+fn()+""

4 returnwrapped5

6 defmakeitalic(fn):7 defwrapped():8 return "" +fn()+""

9 returnwrapped10

11 @makebold12 @makeitalic13 defhello():14 return "hello world"

15

16 print(hello())

hello world

1 #带参数的装饰器

2

3 def makebold(pre=""):4 defprintMakeBold(fn):5 defwrapped():6 print(pre)7 return ""+fn()+""

8 returnwrapped9 returnprintMakeBold10

11 @makebold("测试")12 defprintfn():13 return "helloworld"

14

15 print(printfn())

测试

helloworld

1 #装饰器用于类

2

3 defdecorator(aClass):4 classnewClass:5 def __init__(self,age):6 self.total_display=07 self.wrapped=aClass(age)8 defdisplay(self):9 self.total_display+=1

10 print("total display",self.total_display)11 returnnewClass12

13 @decorator14 classBird:15 def __init__(self,age):16 self.age=age17 defdisplay(self):18 print("my age is",self.age)19

20 eagleLord=Bird(5)21 for i in range(3):22 eagleLord.display()23

24 #在decorator中,我们返回了一个新类newClass。在新类中,我们记录了原来类生成的对象(self.wrapped),并附加了新的属性total_display,用于记录调用display的次数。我们也同时更改了display方法。

25 #26 #27 #通过修改,我们的Bird类可以显示调用display的次数了。

total display 1

total display 2

total display 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值