python - 如何派生带有修饰方法的类?

标签 python oop jinja2 cherrypy

我有几个类似的 python Cherrypy 应用程序

application_one.py

import cherrypy

class Class(object):

    @cherrypy.tools.jinja(a='a', b='b')
    @cherrypy.expose
    def index(self):
        return {
            'c': 'c'
        }

application_two.py

import cherrypy

class Class(object):

    @cherrypy.tools.jinja(a='a2', b='b2')
    @cherrypy.expose
    def index(self):
        return {
            'c': 'c2'
        } 

...

application_n.py

import cherrypy

class Class(object):

    @cherrypy.tools.jinja(a='aN', b='bN')
    @cherrypy.expose
    def index(self):
        return {
            'c': 'cN'
        }

我想创建父类并在所有应用程序中派生它。 像这样的事情

parent.py

import cherrypy

class ParentClass(object):

    _a = None
    _b = None
    _c = None

    @cherrypy.tools.jinja(a=self._a, b=self._b)
    @cherrypy.expose
    def index(self):
        return {
            'c': self._c
        }

application_one.py

import parent

class Class(ParentClass):

    _a = 'a'
    _b = 'b'
    _c = 'c'

application_two.py

import parent

class Class(ParentClass):

    _a = 'a2'
    _b = 'b2'
    _c = 'c2'

如何从派生类发送索引方法装饰器的参数?

现在我收到错误

NameError: name 'self' is not defined

最佳答案

当您定义类时,就会应用装饰器。定义类时,您没有运行方法,因此未定义 self。没有 self 可以引用的实例。

您必须使用元类,它在构建子类时添加装饰器,或者您必须使用类装饰器,它在定义类后应用正确的装饰器。

类装饰器可以是:

def add_decorated_index(cls):
    @cherrypy.tools.jinja(a=cls._a, b=cls._b)
    @cherrypy.expose
    def index(self):
        return {
            'c': self._c
        }

    cls.index = index
    return cls

然后将其应用于子类:

import parent

@parent.add_decorated_index
class Class(parent.ParentClass):
    _a = 'a'
    _b = 'b'
    _c = 'c'

关于python - 如何派生带有修饰方法的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17330242/

相关文章:

python - 是否有基于类属性创建 __init__ 函数的快捷方式?

oop - 使用条目字段作为键的字典数据结构

oop - 绕过 "moving out of borrowed self"检查器的首选模式

python - 如何在使用 jinja2 时将新条目添加到字典对象中?

templates - Jinja 变量的范围可以超出内部 block 吗?

python - 使用 Sharepy 上传多个 Excel 文件到 Sharepoint

python - 告诉 Python 将 .txt 文件保存到 Windows 和 Mac 上的某个目录

python - 如果另一个失败,pytest 可以运行测试吗?

python - 在 python 中操作 Google Cloud Firestore 数据

python-2.7 - Jinja2 无法再找到模板 TemplateNotFound