What Does the "At" (@) Symbol Do in Python?
What Does the @ Symbol Do in Python? 0 15 Answers an @ Symbol at the Beginning of a Line Is Used for Class and Function Decorators: Pep 318: Decorators Python...
What does the @ symbol do in Python?
15 Answers
An @ symbol at the beginning of a line is used for class and function decorators:
The most common Python decorators are:
An @ in the middle of a line is probably matrix multiplication:
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.