2017-10-29 7 views
1

私は学生で、ボトルのマイクロフレームワークで小さなウェブサイトでMVCとOOPを練習したいと思います。デコレータをクラス内で使用する

私のコントローラはボトルオブジェクトをインスタンス化し、それを私のモデルに送信します。私のモデルは、ルーティングを定義するためにBottleクラスの "route"デコレータを使う必要があります(例えば@app.route("/blog"))。

しかし、selfはメソッド外に存在しないため、クラス内でデコレータを使用できないようです。

MVCとOOPのアプローチではどうすればいいですか?私はクラスの外でボトルをインスタンス化し、グローバル変数として使用することを避けたいと思います。

ありがとうございました。

#!/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

関連する問題