首页 > 代码库 > python的callback函数原理

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

 

python的callback函数原理