热线电话:13121318867

登录
2018-12-13 阅读量: 802
python怎么实现装饰器?

功能装饰器

装饰器是一个函数,它将函数作为唯一参数并返回一个函数。这有助于一遍又一遍地使用相同的代码“包装”功能。例如,上面的代码可以重写如下。

我们使用@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")


装饰器也可用于将数据(或添加属性)附加到函数。

# 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)


0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子