gpt4 book ai didi

python - 如何将自己传递给装饰器?

转载 作者:太空狗 更新时间:2023-10-30 01:13:58 25 4
gpt4 key购买 nike

如何将下面的 self.key 传递给装饰器?

class CacheMix(object):

def __init__(self, *args, **kwargs):
super(CacheMix, self).__init__(*args, **kwargs)

key_func = Constructor(
memoize_for_request=True,
params={'updated_at': self.key}
)

@cache_response(key_func=key_func)
def list(self, *args, **kwargs):
pass

class ListView(CacheMix, generics.ListCreateAPIView):
key = 'test_key'

我得到错误:

'self' is not defined

最佳答案

这是一个使用类装饰器实现的示例,正​​如我在评论中试图向您描述的那样。我在你的问题中填写了一些 undefined reference ,并使用了你的 cache_response 函数装饰器的 super 简化版本,但希望这能足够具体地传达这个想法,让你能够适应你的真实情况代码。

import inspect
import types

class Constructor(object):
def __init__(self, memoize_for_request=True, params=None):
self.memoize_for_request = memoize_for_request
self.params = params
def __call__(self):
def key_func():
print('key_func called with params:')
for k, v in self.params.items():
print(' {}: {!r}'.format(k, v))
key_func()

def cache_response(key_func):
def decorator(fn):
def decorated(*args, **kwargs):
key_func()
fn(*args, **kwargs)
return decorated
return decorator

def example_class_decorator(cls):
key_func = Constructor( # define key_func here using cls.key
memoize_for_request=True,
params={'updated_at': cls.key} # use decorated class's attribute
)
# create and apply cache_response decorator to marked methods
# (in Python 3 use types.FunctionType instead of types.UnboundMethodType)
decorator = cache_response(key_func)
for name, fn in inspect.getmembers(cls):
if isinstance(fn, types.UnboundMethodType) and hasattr(fn, 'marked'):
setattr(cls, name, decorator(fn))
return cls

def decorate_me(fn):
setattr(fn, 'marked', 1)
return fn

class CacheMix(object):
def __init__(self, *args, **kwargs):
super(CacheMix, self).__init__(*args, **kwargs)

@decorate_me
def list(self, *args, **kwargs):
classname = self.__class__.__name__
print('list() method of {} object called'.format(classname))

@example_class_decorator
class ListView(CacheMix):
key = 'test_key'

listview = ListView()
listview.list()

输出:

key_func called with params:
updated_at: 'test_key'
list() method of ListView object called

关于python - 如何将自己传递给装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593846/

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