標籤:

跟黃哥學python之類__call__方法

python 內置函數callable,可以檢查一個對象是不是可以被調用(call 這個單詞翻譯成「呼叫」是不是也不錯!)

>>> f = lambda x: x + 1n>>> fn<function <lambda> at 0x1010f7668>n>>> callable(f)nTruen

python中函數、定義了__call__方法的類,實例化後的實例,都是可以被調用的。

函數的情況上面代碼已經演示了callable(f)的返回值為真。

下面看看類的情況。

# coding:utf-8nnnclass Eduction(object):n 黃哥python培訓,黃哥所寫nn def __call__(self):n return "黃哥"nnnp = Eduction()nprint callable(p)nprint p()nn#Truen#黃哥n

下面再看一個__call__ 遞歸調用的例子。

# coding:utf-8nnnclass Factorial(object):n 黃哥python培訓,黃哥所寫nn def __init__(self):n self.cache = {}nn def __call__(self, number):n call 遞歸n if number not in self.cache:n if number == 0:n self.cache[number] = 1n else:n self.cache[number] = number * self.__call__(number-1)n return self.cache[number]nnfact = Factorial()nnprint fact(1)nprint fact(2)nprint fact(3)n# 1n# 2n# 6n

再看看tornado中的代碼。

class WSGIAdapter(object):n """Converts a `tornado.web.Application` instance into a WSGI application.nn Example usage::nn import tornado.webn import tornado.wsgin import wsgiref.simple_servernn class MainHandler(tornado.web.RequestHandler):n def get(self):n self.write("Hello, world")nn if __name__ == "__main__":n application = tornado.web.Application([n (r"/", MainHandler),n ])n wsgi_app = tornado.wsgi.WSGIAdapter(application)n server = wsgiref.simple_server.make_server(, 8888, wsgi_app)n server.serve_forever()nn See the `appengine demon <https://github.com/tornadoweb/tornado/tree/stable/demos/appengine>`_n for an example of using this module to run a Tornado app on Googlen App Engine.nn In WSGI mode asynchronous methods are not supported. This meansn that it is not possible to use `.AsyncHTTPClient`, or then `tornado.auth` or `tornado.websocket` modules.nn .. versionadded:: 4.0n """n def __init__(self, application):n if isinstance(application, WSGIApplication):n self.application = lambda request: web.Application.__call__(n application, request)n else:n self.application = applicationnn def __call__(self, environ, start_response):n method = environ["REQUEST_METHOD"]n uri = urllib_parse.quote(from_wsgi_str(environ.get("SCRIPT_NAME", "")))n uri += urllib_parse.quote(from_wsgi_str(environ.get("PATH_INFO", "")))n if environ.get("QUERY_STRING"):n uri += "?" + environ["QUERY_STRING"]n headers = httputil.HTTPHeaders()n if environ.get("CONTENT_TYPE"):n headers["Content-Type"] = environ["CONTENT_TYPE"]n if environ.get("CONTENT_LENGTH"):n headers["Content-Length"] = environ["CONTENT_LENGTH"]n for key in environ:n if key.startswith("HTTP_"):n headers[key[5:].replace("_", "-")] = environ[key]n if headers.get("Content-Length"):n body = environ["wsgi.input"].read(n int(headers["Content-Length"]))n else:n body = b""n protocol = environ["wsgi.url_scheme"]n remote_ip = environ.get("REMOTE_ADDR", "")n if environ.get("HTTP_HOST"):n host = environ["HTTP_HOST"]n else:n host = environ["SERVER_NAME"]n connection = _WSGIConnection(method, start_response,n _WSGIRequestContext(remote_ip, protocol))n request = httputil.HTTPServerRequest(n method, uri, "HTTP/1.1", headers=headers, body=body,n host=host, connection=connection)n request._parse_body()n self.application(request)n if connection._error:n raise connection._errorn if not connection._finished:n raise Exception("request did not finish synchronously")n return connection._write_buffern

推薦閱讀:

Python 3 實現 Markdown 解析器
量化策略系列教程:13布林強盜系統
Python 抽取word文檔中的文本。
黃哥Python轉載「Python』s super() considered super!」

TAG:Python |