如何用修饰方法派生类?

我有几个类似的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:名称“ self”未定义


阿波罗的战车
浏览 130回答 1
1回答

至尊宝的传说

当您定义类时,将应用装饰器。定义类时,您未在运行方法,因此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_indexclass Class(parent.ParentClass):    _a = 'a'    _b = 'b'    _c = 'c'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python