日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python装饰器由浅入深_由浅入深理解Python装饰器

發(fā)布時間:2024/7/5 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python装饰器由浅入深_由浅入深理解Python装饰器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

前提知識:

1、Python里函數(shù)也是一種對象:

def shout(word="yes"):

return word.capitalize()+"!"

print shout()

# outputs : 'Yes!'

# As an object, you can assign the function to a variable like any

# other object

scream = shout

# Notice we don't use parentheses: we are not calling the function, we are

# putting the function "shout" into the variable "scream".

# It means you can then call "shout" from "scream":

print scream()

# outputs : 'Yes!'

# More than that, it means you can remove the old name 'shout', and

# the function will still be accessible from 'scream'

del shout

try:

print shout()

except NameError, e:

print e

#outputs: "name 'shout' is not defined"

print scream()

# outputs: 'Yes!'

2、Python函數(shù)里面可以定義函數(shù):

def talk():

# You can define a function on the fly in "talk" ...

def whisper(word="yes"):

return word.lower()+"..."

# ... and use it right away!

print whisper()

# You call "talk", that defines "whisper" EVERY TIME you call it, then

# "whisper" is called in "talk".

talk()

# outputs:

# "yes..."

# But "whisper" DOES NOT EXIST outside "talk":

try:

print whisper()

except NameError, e:

print e

#outputs : "name 'whisper' is not defined"*

#Python's functions are objects

3、一個函數(shù)可以返回另外一個函數(shù):

def getTalk(kind="shout"):

# We define functions on the fly

def shout(word="yes"):

return word.capitalize()+"!"

def whisper(word="yes") :

return word.lower()+"...";

# Then we return one of them

if kind == "shout":

# We don't use "()", we are not calling the function,

# we are returning the function object

return shout

else:

return whisper

# How do you use this strange beast?

# Get the function and assign it to a variable

talk = getTalk()

# You can see that "talk" is here a function object:

print talk

#outputs :

# The object is the one returned by the function:

print talk()

#outputs : Yes!

# And you can even use it directly if you feel wild:

print getTalk("whisper")()

#outputs : yes...這意味著可以把函數(shù)當(dāng)做參數(shù)傳遞給其他函數(shù):

def doSomethingBefore(func):

print "I do something before then I call the function you gave me"

print func()

doSomethingBefore(scream)

#outputs:

#I do something before then I call the function you gave me

#Yes!

下面用幾段代碼來由淺入深地理解Python裝飾器:

1、人工賦值的裝飾器:

# A decorator is a function that expects ANOTHER function as parameter

def my_shiny_new_decorator(a_function_to_decorate):

# Inside, the decorator defines a function on the fly: the wrapper.

# This function is going to be wrapped around the original function

# so it can execute code before and after it.

def the_wrapper_around_the_original_function():

# Put here the code you want to be executed BEFORE the original

# function is called

print "Before the function runs"

# Call the function here (using parentheses)

a_function_to_decorate()

# Put here the code you want to be executed AFTER the original

# function is called

print "After the function runs"

# At this point, "a_function_to_decorate" HAS NEVER BEEN EXECUTED.

# We return the wrapper function we have just created.

# The wrapper contains the function and the code to execute before

# and after. It’s ready to use!

return the_wrapper_around_the_original_function

# Now imagine you create a function you don't want to ever touch again.

def a_stand_alone_function():

print "I am a stand alone function, don't you dare modify me"

a_stand_alone_function()

#outputs: I am a stand alone function, don't you dare modify me

# Well, you can decorate it to extend its behavior.

# Just pass it to the decorator, it will wrap it dynamically in

# any code you want and return you a new function ready to be used:

a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)

a_stand_alone_function_decorated()

#outputs:

#Before the function runs

#I am a stand alone function, don't you dare modify me

#After the function runs

a_stand_alone_function重新賦值,這樣每次調(diào)用a_stand_alone_function()的時候就自帶裝飾器了:

a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)

a_stand_alone_function()

#outputs:

#Before the function runs

#I am a stand alone function, don't you dare modify me

#After the function runs

# And guess what? That’s EXACTLY what decorators do!

2、把上面這個例子用裝飾器的語法重寫如下:

@my_shiny_new_decorator

def another_stand_alone_function():

print "Leave me alone"

another_stand_alone_function()

#outputs:

#Before the function runs

#Leave me alone

#After the function runs

我們可以看到裝飾器就是

another_stand_alone_function=my_shiny_new_decorator(another_stand_alone_function) 這句話簡寫

3、我們可以使用多個裝飾器,他們之間是嵌套的順序(從上到下):

def bread(func):

def wrapper():

print "''''''\>"

func()

print ""

return wrapper

def ingredients(func):

def wrapper():

print "#tomatoes#"

func()

print "~salad~"

return wrapper

def sandwich(food="--ham--"):

print food

sandwich()

#outputs: --ham--

sandwich = bread(ingredients(sandwich))

sandwich()

#outputs:

#''''''\>

# #tomatoes#

# --ham--

# ~salad~

#

用裝飾器語法重寫這個例子:

@bread

@ingredients

def sandwich(food="--ham--"):

print food

sandwich()

#outputs:

#''''''\>

# #tomatoes#

# --ham--

# ~salad~

#

裝飾器順序不同,程序運(yùn)行的順序也會不同,例如:

@ingredients

@bread

def strange_sandwich(food="--ham--"):

print food

strange_sandwich()

#outputs:

##tomatoes#

#''''''\>

# --ham--

#

# ~salad~

所以把握好多個裝飾器運(yùn)行的順序是非常重要的。

(本文代碼幾個例子引用自stackoverflow上的一個回答:http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/1594484#1594484)

總結(jié)

以上是生活随笔為你收集整理的python装饰器由浅入深_由浅入深理解Python装饰器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。