Python |集合1中的函数装饰器(简介)

null

出身背景

  1. 在Python中,我们可以在另一个函数中定义一个函数。
  2. 在Python中,一个函数可以作为参数传递给另一个函数(一个函数也可以返回另一个函数)。

# A Python program to demonstrate that a function
# can be defined inside another function and a
# function can be passed as parameter.
# Adds a welcome message to the string
def messageWithWelcome( str ):
# Nested function
def addWelcome():
return "Welcome to "
# Return concatenation of addWelcome()
# and str.
return addWelcome() + str
# To get site name to which welcome is added
def site(site_name):
return site_name
print messageWithWelcome(site( "GeeksforGeeks" ))


输出:

Welcome to GeeksforGeeks

函数装饰器

我们使用@func_name指定要应用于另一个函数的装饰器。

# Adds a welcome message to the string
# returned by fun(). Takes fun() as
# parameter and returns welcome().
def decorate_message(fun):
# Nested function
def addWelcome(site_name):
return "Welcome to " + fun(site_name)
# Decorator returns a function
return addWelcome
@decorate_message
def site(site_name):
return site_name;
# Driver code
# This call is equivalent to call to
# decorate_message() with function
# site("GeeksforGeeks") as parameter
print site( "GeeksforGeeks" )


输出:

Welcome to GeeksforGeeks

decorator在向函数附加数据(或添加属性)时也很有用。

# A Python example to demonstrate that
# decorators can be useful attach data
# A decorator function to attach
# data to func
def attach_data(func):
func.data = 3
return func
@attach_data
def add (x, y):
return x + y
# Driver code
# This call is equivalent to attach_data()
# with add() as parameter
print (add( 2 , 3 ))
print (add.data)


输出:

5
3

“add()”返回作为参数传递的x和y的总和,但它由一个装饰函数包装,调用add(2,3)只会给出两个数字的总和,但当我们调用add时。然后,数据“add”函数被作为参数传递到装饰函数“attach_data”中,该函数返回“add”函数,该函数的属性“data”设置为3,并因此打印它。

Python装饰器是消除冗余的强大工具。

请参考 Python中的装饰器 更多细节。

本文由 Shwetanshu Rohatgi 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享