python装饰器decorator问题

冷风1023 2018-09-28 04:13:50

def my_shiny_new_decorator(a_function_to_decorate):
def the_wrapper_around_the_original_function():
print ("Before the function runs")
a_function_to_decorate()
print ("After the function runs")
return the_wrapper_around_the_original_function

@my_shiny_new_decorator
def another_stand_alone_function():
print ("Leave me alone")
another_stand_alone_function() #这里输如下

#Before the function runs
#Leave me alone
#After the function runs

another_stand_alone_function() #这里的输出还是和上面一样,如果我只想要函数原来的输出,也就是只输出"Leave me alone",怎么做呢?是不是函数被装饰过就不能还原了呢?
...全文
256 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
冷风1023 2018-11-09
  • 打赏
  • 举报
回复
system.ini
冷风1023 2018-09-30
  • 打赏
  • 举报
回复
谢谢4楼,了解了。
混沌鳄鱼 2018-09-29
  • 打赏
  • 举报
回复
装饰器其实只是个语法糖而已,只是 func = decorator(func) 的简便写法,
而且装饰器是在编译阶段就被执行了,因此你说的恢复是不可能的。

如果你还想要保留原始函数只能在装饰前保留一个副本。



import copy

def my_shiny_new_decorator(a_function_to_decorate):
global original_function
original_function = copy.copy(a_function_to_decorate)
def the_wrapper_around_the_original_function():
print("Before the function runs")
a_function_to_decorate()
print("After the function runs")
return the_wrapper_around_the_original_function

def restore_func(a_function_to_restore):
a_function_to_restore = original_function
return a_function_to_restore


@my_shiny_new_decorator
def another_stand_alone_function():
print("Leave me alone")

another_stand_alone_function()

another_stand_alone_function = original_function

another_stand_alone_function() # 这里输如下

# Before the function runs
# Leave me alone
# After the function runs
# Leave me alone

冷风1023 2018-09-29
  • 打赏
  • 举报
回复
回复一楼,怎么去掉呢?我在用完装饰器后,怎么去掉装饰器呢
欢乐的小猪 2018-09-29
  • 打赏
  • 举报
回复
修饰器模式通常用于扩展一个对象的功能。
如果你原来的函数可以满足需求,不必使用装饰器。

Q:修饰器能否有参数?
Answer:可以有参数,例如这个例子True就返回被修饰的函数f,False返回不修饰的原函数。question02.py参考文献:https://pythonconquerstheuniverse.wordpress.com/2012/04/29/python-decorators/
空空夏花 2018-09-28
  • 打赏
  • 举报
回复
把装饰器去掉不就是原来的输出了

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧