您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将自己传递给装饰者?

5b51 2022/1/14 8:23:34 python 字数 3905 阅读 600 来源 www.jb51.cc/python

如何将self.key传递给装饰器? class CacheMix(object): def __init__(self, *args, **kwargs): super(CacheMix, self).__init__(*args, **kwargs) key_func = Construc

概述

如何将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,**kwargs):
            pass

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

我收到错误

'self' is not defined

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,**kwargs):
        super(CacheMix,**kwargs)

    @decorate_me
    def list(self,**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

总结

以上是编程之家为你收集整理的如何将自己传递给装饰者?全部内容,希望文章能够帮你解决如何将自己传递给装饰者?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶