File tree Expand file tree Collapse file tree 1 file changed +49
-1
lines changed
Expand file tree Collapse file tree 1 file changed +49
-1
lines changed Original file line number Diff line number Diff line change 1- #TODO: Add about for this concept.
1+ # About
22
3+ Decorators are a feature of the Python language that can modify or register a function.
4+
5+ ## How to use them
6+
7+ Decorators are placed just above a function in the code like so:
8+
9+ ``` py
10+ @decorator
11+ def function ():
12+ pass
13+ ```
14+
15+ Some decorators take arguments:
16+
17+ ``` py
18+ @decorator2 (name = " Bob" )
19+ def function2 ():
20+ pass
21+ ```
22+
23+ If a decorator takes any arguments, but you don't wish to pass any, you must still call it with parentheses for the decorator to work:
24+
25+ ``` py
26+ @decorator3 ()
27+ def function3 ():
28+ pass
29+ ```
30+
31+ Decorators are just syntactic sugar.
32+ An alternative way of doing the same as the above three examples is using higher-order functions:
33+ ``` py
34+ def function ():
35+ pass
36+
37+ function = decorator(function)
38+
39+
40+ def function2 ():
41+ pass
42+
43+ function2 = decorator2(name = " Bob" )(function2)
44+
45+
46+ def function3 ():
47+ pass
48+
49+ function3 = decorator3()(function3)
50+ ```
You can’t perform that action at this time.
0 commit comments