gpt4 book ai didi

python - Bottle 框架和 OOP,使用方法而不是函数

转载 作者:IT老高 更新时间:2023-10-28 21:48:25 24 4
gpt4 key购买 nike

我已经用 Bottle 编写了一些代码。这真的很简单,适合我的需要。但是,当我尝试将应用程序包装到一个类中时,我被卡住了:

import bottle
app = bottle

class App():
def __init__(self,param):
self.param = param

# Doesn't work
@app.route("/1")
def index1(self):
return("I'm 1 | self.param = %s" % self.param)

# Doesn't work
@app.route("/2")
def index2(self):
return("I'm 2")

# Works fine
@app.route("/3")
def index3():
return("I'm 3")

是否可以在 Bottle 中使用方法而不是函数?

最佳答案

您的代码不起作用,因为您试图路由到非绑定(bind)方法。非绑定(bind)方法没有对 self 的引用,如果没有创建 App 的实例,它们怎么可能?

如果要路由到类方法,首先必须初始化类,然后 bottle.route() 到该对象上的方法,如下所示:

import bottle        

class 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)

不要在 App.__init__() 中执行 bottle.route() 部分,因为您将无法创建App 类的两个实例。

如果你喜欢装饰器的语法而不是设置属性index.route=,你可以写一个简单的装饰器:

def methodroute(route):
def decorator(f):
f.route = route
return f
return decorator

class App(object):
@methodroute('/index/')
def index(self):
pass

关于python - Bottle 框架和 OOP,使用方法而不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8725605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com