gpt4 book ai didi

python - 如何用python类中的方法替换装饰器

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:09 27 4
gpt4 key购买 nike

假设我有以下代码,我在其中使用 get_duration 装饰器打印出方法持续了多长时间。

import datetime
import time

def get_duration(function):
def wrapper(*args, **kwargs):
start = datetime.datetime.now()
print "starting process %s()" %function.__name__
function(*args, **kwargs)
end = datetime.datetime.now()
print "Process lasted: ", end - start
return wrapper

class Operations(object):

def __init__(self, a, b):
self.a = a
self.b = b

@get_duration
def add(self):
time.sleep(1)
print self.a + self.b

@get_duration
def sub(self):
time.sleep(1)
print self.a - self.b


my_class = Operations(2, 98)
my_class.add()
my_class.sub()

输出

>> starting process add()
>> 100
>> Process lasted: 0:00:01.000260
>> starting process sub()
>> -96
>> Process lasted: 0:00:01.001161

我可以用类方法或类似的方法替换它吗(伪代码如下):

my_class = Operations(2, 98)
my_class.add.get_duration #runs add(), prints duration
my_class.add #runs add() does not print duration

最佳答案

要完全按照您的意愿行事,您可以通过可调用类修饰此方法。

class TimeElapser  :
def __init__(self, function_to_wrap) :
self.__call__ = function_to_wrap
self.get_duration = get_duration(function_to_wrap)

例子:

class Foo :

@TimeElapser
def do_something(self, ....) :
...

foo = Foo()
foo.do_something() #Does something
foo.do_something.get_duration() # Does something and print duration

关于python - 如何用python类中的方法替换装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20481027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com