Python decorator? - can someone please explain this?

前端 未结 6 962
离开以前
离开以前 2020-11-29 10:42

Apologies this is a very broad question.

The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protect

6条回答
  •  温柔的废话
    2020-11-29 11:22

    A decorator is a function that takes a function as its only parameter and returns a function. This is helpful to “wrap” functionality with the same code over and over again.

    We use @func_name to specify a decorator to be applied on another function.

    Following example adds a welcome message to the string returned by fun(). Takes fun() as parameter and returns welcome().

    def decorate_message(fun):
    
        # Nested function
        def addWelcome(site_name):
            return "Welcome to " + fun(site_name)
    
        # Decorator returns a function
        return addWelcome
    
    @decorate_message
    def site(site_name):
        return site_name;
    
    print site("StackOverflow")
    
    Out[0]: "Welcome to StackOverflow"
    

    Decorators can also be useful to attach data (or add attribute) to functions.

    A decorator function to attach data to func

    def attach_data(func):
           func.data = 3
           return func
    
    @attach_data
    def add (x, y):
           return x + y
    
    print(add(2, 3))
    # 5    
    print(add.data)
    # 3
    

提交回复
热议问题