Python中装饰器的定义以及用途:
装饰器是一种特殊的函数,它可以接受一个函数作为参数,并返回一个新的函数。装饰器可以用来修改或增强函数的行为,而不需要修改函数本身的代码。在Python中,装饰器通常用于实现AOP(面向切面编程),例如日志记录、性能分析、缓存等。装饰器的语法使用@符号,将装饰器函数放在被装饰函数的定义之前
学过设计模式的朋友都知道,设计模式的结构型模式中也有一个叫装饰器模式,那这个和Python中的装饰器有什么不同呢?
设计模式中的装饰器的定义以及用途:
设计模式中的装饰器是一种结构型模式,它可以在不改变原对象的情况下,为对象添加额外的功能。装饰器模式通常用于在运行时动态地为对象添加功能,而不是在编译时静态地为对象添加功能。装饰器模式通常涉及到多个对象之间的协作,而不是单个函数或对象。
因此,Python中的装饰器和设计模式中的装饰器虽然名称相同,但是它们的实现方式和应用场景有很大的不同。
那Python种的装饰器是怎么实现的呢?先不用着急,我们先来一起学习学习Python中的闭包。
那什么叫做闭包呢?
闭包是指一个函数和它所在的环境变量的组合,即在函数内部定义的函数可以访问外部函数的变量和参数,即使外部函数已经返回。闭包可以用来实现函数式编程中的柯里化、惰性求值、函数组合等高级特性。
看着上面的文字,是不是感觉有点抽象。我说一说我对闭包的理解
闭包是由外部函数和内部函数,内部函数引用到了外部函数定义的变量,外部函数的返回值是内部函数的函数名。对于这样的函数,我们就称为闭包。
好像也有点抽象,我们来看一断代码,就能够理解上面的话了。
def my_decorator(): # my_decorator 这个就叫做外部函数
a = 1
def inner(): # inner 这个叫做内部函数
print(a) # 内部函数引用到了外部函数中定义的变量
return inner # 外部函数的返回值是内部函数名
上面讲解了装饰器的定义、用途,还有闭包,那怎么去实现一个装饰器呢?不急,接下来我们一起来学习如何实现装饰器。
装饰器不是说可以不改变一个函数源代码的基础上,给这个函数添加额外的功能吗?那怎么做呢?
接下来,我们就一起实现一个装饰器,来计算函数的执行时间。Let‘s go!
首先,使用闭包定义一个统计函数执行时间的功能。
def process_time(func):
def inner(*args, **kwargs):
start_time = time.time()
ret = func(*args, **kwargs)
end_time = time.time()
print("函数的执行时间为:%d" % (end_time-start_time))
return ret
return inner
接下来定义一个函数,使用比较来计算函数的执行时间。
import time
def process_time(func):
def inner(*args, **kwargs):
start_time = time.time()
ret = func(*args, **kwargs)
end_time = time.time()
print("函数的执行时间为:%d" % (end_time-start_time))
return ret
return inner
def test(sleep_time):
time.sleep(sleep_time)
t1 = process_time(test)
t1(1)
print("------------")
t1(2)
执行结果:
函数的执行时间为:1
------------
函数的执行时间为:2
通过上面的代码,我们观察到,我们并没有修改test函数的源代码,依旧给test函数添加上了统计函数执行时间的功能。
Python中实现上述功能,有更加优雅的方式。下面,我们就一起来看看如何实现的。
import time
def process_time(func):
def inner(*args, **kwargs):
start_time = time.time()
ret = func(*args, **kwargs)
end_time = time.time()
print("函数的执行时间为:%d" % (end_time-start_time))
return ret
return inner
@process_time
def test(sleep_time):
time.sleep(sleep_time)
test(1)
print("------------")
test(2)
执行结果:
函数的执行时间为:1
------------
函数的执行时间为:2
观察上面的代码变动,发现只有很少的部分修改了。
1、test函数上面添加了一行@process_time。
2、test函数的调用方式发生了改变。
其他的并没有发生变化,整个代码看起来也更加清爽了。
提示:
当使用@装饰器时,会自动执行 闭包中的外部函数内容。这个可以自行验证。
当使用@装饰器时,Python解释器为我们做了什么?
当使用@装饰器时,Python解释器会将被装饰的函数作为参数传递给装饰器函数,并将其返回值作为新的函数对象替换原来的函数对象。这样,每次调用被装饰的函数时,实际上是调用了装饰器函数返回的新函数对象。
Python 装饰器 @ 实际上是一种语法糖,它可以让我们在不改变原函数代码的情况下,对函数进行扩展或修改。当我们使用 @ 装饰器时,实际上是将被装饰函数作为参数传递给装饰器函数,然后将装饰器函数的返回值赋值给原函数名。因此,@ 装饰器并不会进行内存拷贝。
通过下面的函数,可以得知,inner和test函数指向的是同一个内存地址。
import time
def process_time(func):
print("func id --->", id(func))
def inner(*args, **kwargs):
start_time = time.time()
ret = func(*args, **kwargs)
end_time = time.time()
print("函数的执行时间为:%d" % (end_time - start_time))
return ret
print("inner id --->", id(inner))
return inner
@process_time
def test(sleep_time):
print("test func id --->", id(test))
time.sleep(sleep_time)
print("test id --->", id(test))
执行结果:
func id ---> 4312377952
inner id ---> 4313983008
test id ---> 4313983008
使用语法糖时,Python解释器底层为我们做了这样的处理。

上面的两个例子,都只有一个装饰器,是不是Python只能写一个装饰器呢。其实不是的。主要是为了讲解简单。接下来,我们一起来看看,多个装饰器的执行顺序。
def outer_1(func):
print("coming outer_1")
def inner_1():
print("coming inner_1")
func()
return inner_1
def outer_2(func):
print("coming outer_2")
def inner_2():
print("coming inner_2")
func()
return inner_2
def outer_3(func):
print("coming outer_3")
def inner_3():
print("coming inner_3")
func()
return inner_3
@outer_1
@outer_2
@outer_3
def test():
print("coming test")
test()
执行结果:
coming outer_3
coming outer_2
coming outer_1
coming inner_1
coming inner_2
coming inner_3
coming test
outer_3 -> outer_2 -> outer_1 -> inner_1 -> inner_2 -> inner_3 -> 被装饰函数

从上面的执行结果,可以得出如下结论:
使用多个装饰器装饰函数时,
外部函数的执行顺序是从下到上的。
内部函数的执行顺序是从下往上的。
多个装饰器装饰函数时,Python解释器底层做了啥

通过下面这段代码验证
def outer_1(func):
print("coming outer_1, func id -->", id(func))
def inner_1():
print("coming inner_1")
func()
print("inner_1 id -->", id(inner_1))
return inner_1
def outer_2(func):
print("coming outer_2, func id -->", id(func))
def inner_2():
print("coming inner_2")
func()
print("inner_2 id -->", id(inner_2))
return inner_2
def outer_3(func):
print("coming outer_3, func id -->", id(func))
def inner_3():
print("coming inner_3")
func()
print("inner_3 id -->", id(inner_3))
return inner_3
@outer_1
@outer_2
@outer_3
def test():
print("coming test")
test()
执行结果:
coming outer_3, func id --> 4389102784
inner_3 id --> 4389102928
coming outer_2, func id --> 4389102928
inner_2 id --> 4389103072
coming outer_1, func id --> 4389103072
inner_1 id --> 4389103216
coming inner_1
coming inner_2
coming inner_3
coming test
该如何实现带参数的装饰器呢,其实原理一样的,我们再定义一个外层函数,外层函数的返回值是内存函数的名称,即引用。
下面我们来看一个例子:
def is_process(flag):
def outer_1(func):
print("coming outer_1, func id -->", id(func))
def inner_1():
print("coming inner_1")
if flag:
func()
print("inner_1 id -->", id(inner_1))
return inner_1
return outer_1
@is_process(True)
def test():
print("coming test")
test()
注意:
@is_process(True),这里是调用了is_process这个函数猜一猜下面函数会输出什么?
def outer_1(func):
def inner_1():
print("inner_1, func __name__", func.__name__)
print("inner_1, func __doc__", func.__doc__)
func()
return inner_1
@outer_1
def test():
"""this is test"""
print("outer_1, func __name__", test.__name__)
print("outer_1, func __doc__", test.__doc__)
test()
函数执行结果:
inner_1, func __name__ test
inner_1, func __doc__ this is test
test, test __name__ inner_1
test, test __doc__ None
注意到没,在test函数体内打印函数的 __name__、__doc__ 属性,居然变成内部函数的了。
这个是为什么呢?
Python装饰器在装饰函数时,会将原函数的函数名、文档字符串、参数列表等属性复制到装饰器函数中,但是装饰器函数并不会复制原函数的所有属性。例如,原函数的name属性、doc属性、module属性等都不会被复制到装饰器函数中。
为了避免这种情况,可以使用functools库中的wraps装饰器来保留原来函数对象的属性。wraps装饰器可以将原来函数对象的属性复制到新的函数对象中,从而避免属性丢失的问题。
from functools import wraps
def outer_1(func):
@wraps(func)
def inner_1():
print("inner_1, func __name__", func.__name__)
print("inner_1, func __doc__", func.__doc__)
func()
return inner_1
@outer_1
def test():
"""this is test"""
print("test, test __name__", test.__name__)
print("test, test __doc__", test.__doc__)
test()
执行结果:
inner_1, func __name__ test
inner_1, func __doc__ this is test
test, test __name__ test
test, test __doc__ this is test
上面我们都是使用的函数来实现装饰器的功能,那可不可以用类来实现装饰器的功能呢?我们知道函数实现装饰器的原理是外部函数的参数是被装饰的函数,外部函数返回内部函数的名称。内部函数中去执行被装饰的函数。
那么其实类也是可以用来实现装饰器的,因为当我们为 类 定义了 __call__方法时,这个类就成了可调用对象,实例化后可直接调用。
class ProcessTime:
def __call__(self, *args, **kwargs):
print("call")
p = ProcessTime()
p()
import time
class ProcessTime:
def __init__(self, func):
print("coming ProcessTime __init__")
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
ret = self.func(*args, **kwargs)
end_time = time.time()
print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
return ret
@ProcessTime
def test(sleep_time):
time.sleep(sleep_time)
return "tet"
test(1)
执行结果:
coming ProcessTime __init__
coming ProcessTime __call__, id(self.func) --> 4488922160
ProcessTime 函数的执行时间为:1
通过上面的执行结果,我们可以得到,@ProcessTime的作用是 test = ProcessTime(test)。又因为 ProcessTime定义了__call__方法,是可调用对象,所以可以像函数那样直接调用实例化ProcessTime后的对象。
这里可以验证,通过注释掉装饰器,手动初始化ProcessTime类。得到的结果是一样的。
# @ProcessTime
def test(sleep_time):
time.sleep(sleep_time)
return "tet"
test = ProcessTime(test)
test(1)
多个类装饰器的执行顺序是怎么样的呢,这里我们也通过代码来进行验证。
import time
class ProcessTime:
def __init__(self, func):
print("coming ProcessTime __init__", id(self))
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
ret = self.func(*args, **kwargs)
end_time = time.time()
print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
return ret
class ProcessTime2:
def __init__(self, func):
print("coming ProcessTime2 __init__", id(self))
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
print("coming ProcessTime2 __call__, id(self.func) -->", id(self.func))
ret = self.func(*args, **kwargs)
end_time = time.time()
print("ProcessTime2 函数的执行时间为:%d" % (end_time - start_time))
return ret
@ProcessTime
@ProcessTime2
def test(sleep_time):
time.sleep(sleep_time)
return "tet"
# test = ProcessTime2(test)
# test = ProcessTime(test)
t = test(1)
执行结果:
coming ProcessTime2 __init__ 4472235104
coming ProcessTime __init__ 4473162672
coming ProcessTime __call__, id(self.func) --> 4472235104
coming ProcessTime2 __call__, id(self.func) --> 4471735344
ProcessTime2 函数的执行时间为:1
ProcessTime 函数的执行时间为:1
从上面的结果,我们得到,执行顺序是:
ProcessTime2 中的__init__ -> ProcessTime 中的__init__ -> ProcessTime 中的__call__ -> ProcessTime2 中的__call__
特别注意:
ProcessTime 中的__call__中的代码并不会执行完后再去执行ProcessTime2 中的__call__,而是在调用ret = self.func(*args, **kwargs)方法后,就回去执行ProcessTime2 中的__call__的代码。
其实,类装饰器也存在和函数装饰器一样的问题。它会覆盖原函数的元数据信息,例如函数名、文档字符串、参数列表等。这可能会导致一些问题,例如调试时无法正确显示函数名、文档生成工具无法正确生成文档等。
import time
from functools import wraps
class ProcessTime:
def __init__(self, func):
print("coming ProcessTime __init__", id(self))
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
ret = self.func(*args, **kwargs)
end_time = time.time()
print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
return ret
@ProcessTime
def test(sleep_time):
"tets"
print("test.__doc__", test.__doc__)
# print(test.__name__) --> 报错,AttributeError: 'ProcessTime' object has no attribute '__name__'
time.sleep(sleep_time)
return "tet"
t = test(1)
那类装饰器该如何解决呢?
我现在还不知道该如何处理,如果有知道的朋友,请不吝赐教,十分感谢!!
其实,我觉得不用特别的去记多个装饰器的执行顺序是如何的,我们最重要的是理解到装饰器的执行逻辑是如何的。函数装饰器和类装饰器的初始化顺序都是一样的:从靠近被装饰的函数开始执行初始化操作。把这个核心原理理解到后,多个装饰器的执行顺序在使用的时候,就很容易得到了。

总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只