2017-10-29 85 views
1

我是一名學生,我想用一個帶有微縮框架的小網站練習MVC和OOP。在課堂上和自己一起使用裝飾器

所以我的控制器實例化一個Bottle對象,並將其發送給我的模型。我的模型需要使用Bottle類的「路由」裝飾器來定義路由(例如,@app.route("/blog"))。

但它看起來像我不能在類中使用裝飾器,因爲self不存在方法外。

那麼我怎麼能在MVC和OOP方法中做到這一點?即我想避免在一個類之外實例化Bottle並將其用作全局變量。

謝謝。

#!/usr/bin/env python 
#-*-coding:utf8-*- 

from bottle import Bottle, run 




class Model(): 
    def __init__(self, app): 
     self.app = app 


    @self.app.route("/hello") ### dont work because self dont exist here 
    def hello(self): 
     return "hello world!" 


class View(): 
    pass 


class Controller(): 
    def __init__(self): 
     self.app = Bottle() 
     self.model=Model(self.app) 



if __name__ == "__main__": 
    run(host="localhost", port="8080", debug=True) 

回答

1

方式一:

class Model(object): 
    def __init__(self, app): 
     self.app = app 
     self.hello = self.app.route("/hello")(self.hello) 

    def hello(self): 
     return "hello world!" 
+0

還不錯,謝謝 – vildric