You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: sections/software-design-1.qmd
+39-2Lines changed: 39 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -39,12 +39,22 @@ Functions are first-class objects in Python (and many other languages). This has
39
39
def double(x):
40
40
return 2*x
41
41
42
+
print(double)
43
+
```
44
+
45
+
```{python}
42
46
# also assign the function to the `twotimes` variable
43
47
twotimes = double
44
48
type(twotimes)
45
49
```
46
50
47
-
Note that when we print it to screen, we see that `prod` is of type `function`, and when we use the two instances, we get identical results:
51
+
Note that when we print it to screen, we see that `prod` is of type `function`. We can see from the object address that it is the same object as `double`:
52
+
53
+
```{python}
54
+
print(twotimes)
55
+
```
56
+
57
+
and when we use the two instances, we get identical results:
48
58
49
59
```{python}
50
60
print(double(7))
@@ -81,7 +91,32 @@ Note how we passed the `some_function` as a variable name without the parenthese
81
91
::: {.callout-note}
82
92
83
93
### Decorators
84
-
This approach to function composition is exactly what is used by [Python decorator](https://docs.python.org/3/glossary.html#term-decorator) functions.
94
+
95
+
This approach to function composition is exactly what is used by [Python decorator](https://docs.python.org/3/glossary.html#term-decorator) functions. A `decorator` in python is a function that returns a function, thereby making it easy to wrap the one function inside another. To modify our above exmaple into a decorator, we can simply return the `wrapper` function:
96
+
97
+
```{python}
98
+
def my_decorator(func_to_run):
99
+
def wrapper():
100
+
print("Ran wrapper")
101
+
func_to_run()
102
+
print("Finished wrapper")
103
+
return wrapper
104
+
105
+
f = my_decorator(some_function)
106
+
107
+
f()
108
+
```
109
+
110
+
Finally, once you have a decorator function defined, you can easily apply it to your functions when you define them using some special syntactic sugar, the `@` annotation.
111
+
112
+
```{python}
113
+
@my_decorator
114
+
def hello():
115
+
print("Hello")
116
+
117
+
hello()
118
+
119
+
```
85
120
86
121
:::
87
122
@@ -200,4 +235,6 @@ Deadlocks occur when two concurrent tasks block on the output of the other. Dead
0 commit comments