为了账号安全,请及时绑定邮箱和手机立即绑定

如何用修饰方法派生类?

如何用修饰方法派生类?

阿波罗的战车 2021-03-29 17:14:05
我有几个类似的python cherrypy应用程序application_one.pyimport cherrypyclass Class(object):    @cherrypy.tools.jinja(a='a', b='b')    @cherrypy.expose    def index(self):        return {            'c': 'c'        }application_two.pyimport cherrypyclass Class(object):    @cherrypy.tools.jinja(a='a2', b='b2')    @cherrypy.expose    def index(self):        return {            'c': 'c2'        } ....application_n.pyimport cherrypyclass Class(object):    @cherrypy.tools.jinja(a='aN', b='bN')    @cherrypy.expose    def index(self):        return {            'c': 'cN'        }我想成为父类并在所有应用程序中派生它。像这样parent.pyimport cherrypyclass 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.pyimport parentclass Class(ParentClass):    _a = 'a'    _b = 'b'    _c = 'c'application_two.pyimport parentclass Class(ParentClass):    _a = 'a2'    _b = 'b2'    _c = 'c2'如何从派生类发送用于索引方法修饰符的参数?现在我得到错误NameError:名称“ self”未定义
查看完整描述

1 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

当您定义类时,将应用装饰器。定义类时,您未在运行方法,因此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'


查看完整回答
反对 回复 2021-04-06
  • 1 回答
  • 0 关注
  • 130 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号