How to use decorators to register callback functions in Python

I have always known that decorators can enhance an existing method. Python also provides an annotation method, which is very useful. But when looking at the flask login extension package, I found that the decorator can also implement the registration function of the callback function.

 

Flask login is to register the callback function through the following decorator. When there is no sessionID, the user is read into the session through the function specified by the decorator.

@login_manager.user_loader

 

A simple test example is written below to demonstrate this functionality.

 

import time
import functools
class Test():
   
    #/**feature will call callback(), but callback is not really defined in Test**/
    def feature(self):
        self.callback()
    
    def decorate(self, func):
        self.callback=func
        return func

test =  Test()


#/**Register foo as a callback function*//
@test.decorate
def foo():
    print 'in foo()'

#/**Calling the feature will trigger the callback function**/    
test.feature()

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326803026&siteId=291194637