[英]use decorator with self in class
I am a student and I want to practice MVC and OOP with a little website with the Bottle microframework.我是一名学生,我想通过一个带有 Bottle 微框架的小网站来练习 MVC 和 OOP。
So my controller instantiate a Bottle object, and send it to my model.所以我的控制器实例化一个 Bottle 对象,并将它发送到我的模型。 My model need to use the "route" decorator of the Bottle class to define routing (
@app.route("/blog")
for example).我的模型需要使用 Bottle 类的“路由”装饰器来定义路由(例如
@app.route("/blog")
)。
But it looks like I cant use a decorator in a class because self
dont exist outside a method.但看起来我不能在类中使用装饰器,因为
self
不存在于方法之外。
So how can I do that in a MVC and OOP approach?那么我怎样才能在 MVC 和 OOP 方法中做到这一点呢? ie I would like to avoid to instantiate Bottle outside a class and use it as a global variable.
即我想避免在类之外实例化 Bottle 并将其用作全局变量。
Thanks.谢谢。
#!/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)
One way:单程:
class Model(object):
def __init__(self, app):
self.app = app
self.hello = self.app.route("/hello")(self.hello)
def hello(self):
return "hello world!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.