1. 程式人生 > >python基礎:裝飾器

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)

本文出自 “回首已是空” 博客,請務必保留此出處http://yishi.blog.51cto.com/1059986/1983475

python基礎:裝飾器