2013-06-26 45 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'