2013-06-26 106 views
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' 
     } 

我想製作父類並在所有應用程序中派生它。 像這樣

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' 

如何發送PARAM從派生類的索引方法裝飾器?

現在,我得到錯誤

NameError: name 'self' is not defined

回答

2

裝飾應用當你定義類。定義一個類時,你沒有運行一個方法,因此沒有定義selfself沒有實例可供參考。

您不得不使用元類,而是在構建子類時添加裝飾器,或者您必須使用類裝飾器,該類裝飾器會在定義類後應用正確的裝飾器。

類裝飾可能是:

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'