2

私はいくつかの同様の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'
        }

親クラスを作成し、すべてのアプリケーションで派生させたい。このようなもの

親.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' が定義されていません

4

1 に答える 1

2

class を定義すると、デコレータが適用されます。クラスを定義するときは、メソッドを実行していないため、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'
于 2013-06-26T21:31:24.177 に答える