hailai 发表于 2018-8-10 07:18:18

python基础:装饰器

  一、定义:
  是一个传入值是函数,返回值也是函数的高阶函数。
  二、作用:
  不改变原函数的代码和调用方式,增加新的功能。
  三、实例:
  把两个函数earth()和moon()添加print('They are in the solar system!')
  1、定义两个函数,分别有自己的功能:
def earth():  
print('This is earth!')
  

  
def moon():
  
print('This is moon!')
  

  
earth()
  
moon()
  运行结果:
This is earth!  
This is moon!
  2、在不改变当前函数代码,和调用方式情况下,加一个打印太阳系的功能。
def add_func(func):                      # func是一个函数体,func()是运行函数  
def solar():
  
print('It is in the solar system!')
  
func()
  
return solar                            # 返回solar函数,earth = solar
  

  
@add_func                              # 此句功能func = earth
  
def earth():
  
print('This is earth!')
  

  
@add_func
  
def moon():
  
print('This is moon!')
  

  
earth()
  
moon()
  运行结果:
It is in the solar system!  
This is earth!
  
It is in the solar system!
  
This is moon!
  每次调用earth()和moon(),都会增加打印It is in the solar system!这句。
  原理:
  和交换a,b值原理是一样的,首先,把earth函数地址保存到func,再把solar的地址保存到earth,这时候然后再调用earth,实际运行的是solar,再在solar里调用func,实现原来的功能。
  函数,例如earth(),不带括号,可以理解成变量名;   带括号,运行函数,返回函数运行结果。
  3、如果原函数带参数,最里面的func()也需要带参数。
name = 'earth'  
def add_func(func):
  
def solar():
  
print('It is in the solar system!')
  
func(name)                            # 带参数!!!!!!!
  
print('1:',solar)
  
return solar
  

  
@add_func
  
def earth(name):                        # 带参数!!!!!!!
  
print('This is %s!' % name)
  
print('2:',earth)
  

  
earth()
  如果多个函数使用同一个装饰器,并且这些函数参数的数量不同,func()可以使用变长形式func(*args, **kwargs)
页: [1]
查看完整版本: python基础:装饰器