【问题标题】:Class decorator object has no attribute __name__类装饰器对象没有属性 __name__
【发布时间】:2014-10-02 11:12:57
【问题描述】:

我写了一个装饰器类,如下所示:

import functools

class ViewCounter(object):
    def __init__(self,user_slug=None):
        self.user_slug = user_slug

    def __call__(self, func):
        @functools.wraps(func)
        def wrapped_func(*args, **kwargs):
            return func(*args,**kwargs)
        return wrapped_func

我已使用 Django 的method_decorator 将其应用于我的一个基于类的视图,如下所示:

class ProjectPage(DetailView):
    template_name = 'account/profile-page-latest.html'
    model = User
    context_object_name = 'user_obj'

    @method_decorator(ViewCounter) 
    def dispatch(self, *args, **kwargs):
        return super(ProjectPage, self).dispatch(*args, **kwargs)

我在控制台中收到此错误:

AttributeError: 'ViewCounter' object has no attribute '__name__'

【问题讨论】:

  • 什么是method_decorator?如果它来自this module,那么非常简短的文档建议您应该继承它,而不是调用它(但我自己没有任何第一手经验)。
  • 从 django.utils.decorators 导入 method_decorator .. 它从这里 .. @Blckknght

标签: python django python-2.7 python-decorators


【解决方案1】:

我相信使用@method_decorator(ViewCounter()) 应该可以解决问题。 ViewCounter 不是函数装饰器,它是一个类,其实例是函数装饰器。

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2019-11-13
    相关资源
    最近更新 更多