我无法理解functools中的部分工作原理.我从这里得到以下代码:
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>>> incr2 = functools.partial(sum2, 1)
>>> incr2(4)
5
Run Code Online (Sandbox Code Playgroud)
现在就行了
incr = lambda y : sum(1, y)
Run Code Online (Sandbox Code Playgroud)
我得到的是,无论我传递给incr它的任何论点都将被传递y给lambda哪个将返回sum(1, y)ie 1 + y.
我明白那个.但我不明白这一点incr2(4).
如何在部分函数中4传递x?对我来说,4应该更换sum2.x和之间有什么关系 …
我有这个基本的 python3 服务器,但不知道如何提供目录。
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going Up')
if self.path == '/down':
self.send_response(200)
self.end_headers()
self.wfile.write(B'Going Down')
httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)
如果不是上面的自定义类,我只是简单地传入Handler = http.server.SimpleHTTPRequestHandlerTCPServer():,默认功能是提供一个目录,但我想提供该目录并在上面的两个 GET 上提供功能。
例如,如果有人要访问 localhost:8080/index.html,我希望将该文件提供给他们
我正在整理一个涉及GUI,HTTP和TCP服务器的小应用程序.GUI控制从HTTP和TCP服务器返回到客户端的响应.我使用HTTPServer和SocketServer.TCPServer类作为服务器,具有BaseHTTPRequestHandler和StreamRequestHandler的子类.但是让我们首先关注事物的HTTP方面.
当HTTPServer收到请求时,它应该检查GUI的状态,并做出适当的响应.我已经将一个成员变量添加到指向GUI的HTTPServer,但是无法找到从BaseHTTPRequestHandler子类访问该字段的好方法.如何才能做到这一点?
下面是我目前的代码,虽然Python抛出异常,MyHTTPHandler instance has no attribute 'server':
class MyHTTPHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
self._server = server
def do_GET(self):
self._server.get_interface().do_something()
[...]
Run Code Online (Sandbox Code Playgroud)