Python 装饰器 - <Classname> 对象没有属性“__name__”

Python Decorators - <Classname> object has no attribute '__name__'

我有一个像下面这样的龙卷风方法,我试图装饰方法来缓存东西。我有以下设置

def request_cacher(x):
    def wrapper(funca):
        @functools.wraps(funca)
        @asynchronous
        @coroutine
        def wrapped_f(self, *args, **kwargs):
            pass

        return wrapped_f
    return wrapper

class PhotoListHandler(BaseHandler):
    @request_cacher
    @auth_required
    @asynchronous
    @coroutine
    def get(self):
        pass

我收到错误,AttributeError: 'PhotoListHandler' object has no attribute '__name__' 有什么想法吗?

我认为这可能适合你,

import tornado.ioloop
import tornado.web
from tornado.gen import coroutine
from functools import wraps


cache = {}

class cached(object):
    def __init__ (self, rule, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.rule = rule
        cache[rule] = 'xxx'

    def __call__(self, fn):
        def newf(*args, **kwargs):
            slf = args[0]
            if cache.get(self.rule):
                slf.write(cache.get(self.rule))
                return
            return fn(*args, **kwargs)
        return newf 


class MainHandler(tornado.web.RequestHandler):

    @coroutine
    @cached('/foo')
    def get(self):
        print "helloo"
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

您的代码从 functools.wraps(funca) 抛出,因此 funca 必须是一个 PhotoListHandler 实例,而不是您想要的包装 get 方法。我相信这意味着堆栈中的下一个装饰器 auth_required 写错了:auth_required 返回 self 而不是返回函数。

虽然我在这里:在经过身份验证的函数之上堆叠缓存对我来说是错误的。不会缓存第一个经过身份验证的用户的照片列表,然后显示给所有后续用户吗?

问题是您将 request_cacher 装饰器定义为带有参数的装饰器,但您忘记传递参数了!

考虑这段代码:

import functools


def my_decorator_with_argument(useless_and_wrong):
    def wrapper(func):
        @functools.wraps(func)
        def wrapped(self):
            print('wrapped!')
        return wrapped
    return wrapper


class MyClass(object):
    @my_decorator_with_argument
    def method(self):
        print('method')


    @my_decorator_with_argument(None)
    def method2(self):
       print('method2')

当您尝试在实例中使用 method 时,您会得到:

>>> inst = MyClass()
>>> inst.method    # should be the wrapped function, not wrapper!
<bound method MyClass.wrapper of <bad_decorator.MyClass object at 0x7fed32dc6f50>>
>>> inst.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "bad_decorator.py", line 6, in wrapper
    @functools.wraps(func)
  File "/usr/lib/python2.7/functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'MyClass' object has no attribute '__name__'

装饰器的正确用法:

>>> inst.method2()
wrapped!

替代修复方法是从装饰器中删除一层:

def my_simpler_decorator(func):
    @functools.wraps(func)
    def wrapped(self):
        print('wrapped!')
    return wrapped


class MyClass(object):

    @my_simpler_decorator
    def method3(self):
        print('method3')

你可以看到它没有引发错误:

>>> inst = MyClass()
>>> inst.method3()
wrapped!