What does the “at” (@) symbol do in Python?

前端 未结 12 1301
萌比男神i
萌比男神i 2020-11-22 01:57

I\'m looking at some Python code which used the @ symbol, but I have no idea what it does. I also do not know what to search for as searching Python docs or Goo

12条回答
  •  佛祖请我去吃肉
    2020-11-22 02:36

    What does the “at” (@) symbol do in Python?

    @ symbol is a syntactic sugar python provides to utilize decorator,
    to paraphrase the question, It's exactly about what does decorator do in Python?

    Put it simple decorator allow you to modify a given function's definition without touch its innermost (it's closure).
    It's the most case when you import wonderful package from third party. You can visualize it, you can use it, but you cannot touch its innermost and its heart.

    Here is a quick example,
    suppose I define a read_a_book function on Ipython

    In [9]: def read_a_book():
       ...:     return "I am reading the book: "
       ...: 
    In [10]: read_a_book()
    Out[10]: 'I am reading the book: '
    

    You see, I forgot to add a name to it.
    How to solve such a problem? Of course, I could re-define the function as:

    def read_a_book():
        return "I am reading the book: 'Python Cookbook'"
    

    Nevertheless, what if I'm not allowed to manipulate the original function, or if there are thousands of such function to be handled.

    Solve the problem by thinking different and define a new_function

    def add_a_book(func):
        def wrapper():
            return func() + "Python Cookbook"
        return wrapper
    

    Then employ it.

    In [14]: read_a_book = add_a_book(read_a_book)
    In [15]: read_a_book()
    Out[15]: 'I am reading the book: Python Cookbook'
    

    Tada, you see, I amended read_a_book without touching it inner closure. Nothing stops me equipped with decorator.

    What's about @

    @add_a_book
    def read_a_book():
        return "I am reading the book: "
    In [17]: read_a_book()
    Out[17]: 'I am reading the book: Python Cookbook'
    

    @add_a_book is a fancy and handy way to say read_a_book = add_a_book(read_a_book), it's a syntactic sugar, there's nothing more fancier about it.

提交回复
热议问题