如何把自己变成一个装饰师?

2024-04-19 08:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将下面的self.key传递到decorator?在

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'

我得到了一个错误:

^{pr2}$

Tags: keyselfforobjectinitdefargsdecorator
2条回答

下面是一个用类修饰符来做的例子,正如我在评论中所描述的那样。我在您的问题中填写了一些未定义的引用,并使用了您的cache_response函数修饰符的超级简化版本,但希望这能具体地传达您的想法,使您能够将其适应您的实际代码。在

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

输出:

^{pr2}$

或者像你发现的那个函数:

def decorator(the_func):
    @wraps(the_func)
    def wrapper(*args, **kwargs):
        the_func(*args, **kwargs)
    return wrapper

而修饰任何以self作为参数的方法,self都会出现在args中。因此,您可以这样做:

^{pr2}$

像平常一样叫它

foo = myClass()
foo.myFunction()

你应该得到

Hello
World

相关问题 更多 >