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

前端 未结 12 1294
萌比男神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:32

    Example

    class Pizza(object):
        def __init__(self):
            self.toppings = []
    
        def __call__(self, topping):
            # When using '@instance_of_pizza' before a function definition
            # the function gets passed onto 'topping'.
            self.toppings.append(topping())
    
        def __repr__(self):
            return str(self.toppings)
    
    pizza = Pizza()
    
    @pizza
    def cheese():
        return 'cheese'
    @pizza
    def sauce():
        return 'sauce'
    
    print pizza
    # ['cheese', 'sauce']
    

    This shows that the function/method/class you're defining after a decorator is just basically passed on as an argument to the function/method immediately after the @ sign.

    First sighting

    The microframework Flask introduces decorators from the very beginning in the following format:

    from flask import Flask
    app = Flask(__name__)
    
    @app.route("/")
    def hello():
        return "Hello World!"
    

    This in turn translates to:

    rule      = "/"
    view_func = hello
    # They go as arguments here in 'flask/app.py'
    def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
        pass
    

    Realizing this finally allowed me to feel at peace with Flask.

提交回复
热议问题