python的callback函数原理
__getattribute__作用
""" class C(object): a = 'abc' def __getattribute__(self, *args, **kwargs): print("__getattribute__() is called") print args if args[0] == 'a': return object.__getattribute__(self, *args, **kwargs) else: print '调用函数foo()' return object.__getattribute__(self,'foo')() def foo(self): return "hello" if __name__ == '__main__': c = C() print c.foo """
callback
class Callback: def __init__(self, instance, function_name): self.instance = instance # api.self self.function_name = function_name # function def action(self, params): print self.instance.__getattribute__(self.function_name) self.instance.__getattribute__(self.function_name)(params) class Test: def __init__(self): self.clb = None def register(self, clb): self.clb = clb # Callback(self, self.function.__name__) def do_test(self): params = [] self.clb.action(params) class Api(object): def __init__(self, test_instance): test_instance.register(Callback(self, self.function.__name__)) def function(self, params): print params print('function') t = Test() a = Api(t) t.do_test()
第二种callback制造方法
import errno import functools import tornado.ioloop import socket def connection_ready(sock, fd, events): while True: try: connection, address = sock.accept() except socket.error as e: if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): raise return connection.setblocking(0) handle_connection(connection, address) if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) sock.bind(("", port)) sock.listen(128) io_loop = tornado.ioloop.IOLoop.current() # IOLoop() callback = functools.partial(connection_ready, sock) io_loop.add_handler(sock.fileno(), callback, io_loop.READ) io_loop.start()
还有一种比较不错的回调函数
作者:沐禹辰
出处:http://www.cnblogs.com/renfanzi/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
出处:http://www.cnblogs.com/renfanzi/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。