您的代码不起作用,因为您尝试路由到非绑定方法。非绑定方法没有对的引用
self,如果
App尚未创建的实例,怎么办?
如果要路由到类方法,则首先必须初始化类,然后再初始化
bottle.route()到该对象上的方法,如下所示:
import bottleclass App(object): def __init__(self,param): self.param = param def index1(self): return("I'm 1 | self.param = %s" % self.param)myapp = App(param='some param')bottle.route("/1")(myapp.index1)如果要在处理程序附近添加路由定义,可以执行以下操作:
def routeapp(obj): for kw in dir(app): attr = getattr(app, kw) if hasattr(attr, 'route'): bottle.route(attr.route)(attr)class App(object): def __init__(self, config): self.config = config def index(self): pass index.route = '/index/'app = App({'config':1})routeapp(app)不要做中的bottle.route()
部分App.__init__()
,因为您将不能创建两个App
类的实例。
如果您比装饰属性更喜欢装饰器的语法
index.route=,可以编写一个简单的装饰器:
def methodroute(route): def decorator(f): f.route = route return f return decoratorclass App(object): @methodroute('/index/') def index(self): pass


