我通常在裸脚本中使用bottle
:
import bottle
@bottle.route('/ping')
def ping():
return "pong"
bottle.run()
它工作正常,调用 http://127.0.0.1:8080/ping
返回 pong
。我现在想使用一个类来实现相同的功能:
import bottle
class PingPong:
@bottle.route('/ping')
def ping(self):
return "pong"
def run(self):
bottle.run()
if __name__ == "__main__":
p = PingPong()
p.run()
调用 http://127.0.0.1:8080/ping
现在返回 500
并且服务器上的回溯是
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\bottle.py", line 862, in _handle
return route.call(**args)
File "C:\Python34\lib\site-packages\bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
TypeError: ping() missing 1 required positional argument: 'self'
127.0.0.1 - - [28/Dec/2015 19:15:15] "GET /ping HTTP/1.1" 500 745
如果我从方法定义中删除 self
,服务器工作正常。
为什么在这种情况下 self 参数是多余的?这与默认传递 self 并对应于方法调用中的“无参数”的普通方法有何不同?
最佳答案
那是因为 bottle 不知道你传递的函数是一个方法,它没有方法的概念。另外,问问自己:bottle 应该自动创建实例吗?
如果您想使用绑定(bind)实例方法,请改为执行此操作:
class PingPong:
def ping(self):
return "pong"
def run(self):
bottle.route('/ping', callback=self.ping)
bottle.run()
if __name__ == "__main__":
p = PingPong()
p.run()
也就是说,在实例初始化后,将绑定(bind)方法传递给 route()
。
关于python - 为什么在类里面使用 bottle 时 self 对于方法来说是多余的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34498680/