|
20 | 20 | * [String formatting](#string-formatting)
|
21 | 21 | * [Function](#function)
|
22 | 22 | * [Function Call](#function-call)
|
| 23 | + * [Function as Object](#function-as-object) |
| 24 | + * [Nested Function](#nested-function) |
| 25 | + * [Lambda](#lambda) |
23 | 26 | * [Data Structures](#data-structures)
|
24 | 27 | * [Lists](#lists)
|
25 | 28 | * [Dictionaries](#dictionaries)
|
@@ -227,6 +230,46 @@ print( "Subtraction - {} minus {}: {}" . format( b, a, e ) ) # Subtraction - 50
|
227 | 230 | print( "Person - {}" . format( p ) ) # Person - {'name': 'Joe', 'age': 75}
|
228 | 231 | ```
|
229 | 232 |
|
| 233 | +### Function as Object |
| 234 | +All data in a Python is represented by objects. There’s nothing particularly special about functions. They’re also just objects. |
| 235 | +```python |
| 236 | +def yell(text): # Define function yell |
| 237 | + return text.upper() + '!' |
| 238 | + |
| 239 | + |
| 240 | +>>> bark = yell # Declare an object "bark" that contains the function "yell" |
| 241 | +>>> bark('woof') # You could now execute the "yell" function object by calling bark |
| 242 | +'WOOF!' |
| 243 | +``` |
| 244 | + |
| 245 | +### Nested Function |
| 246 | +Functions can be defined inside other functions. These are often called nested functions or inner functions. |
| 247 | +```python |
| 248 | +def speak(text): # Define function speak |
| 249 | + def wisper(t): # Function wisper does not exist outside speak |
| 250 | + return t.lower() + '...' |
| 251 | + return wisper(text) |
| 252 | + |
| 253 | + |
| 254 | +>>> speak('Hello, World') |
| 255 | +'hello, world...' |
| 256 | +``` |
| 257 | + |
| 258 | +## Lambda |
| 259 | +The lambda keyword in Python provides a shortcut for declaring small anonymous functions. |
| 260 | +```python |
| 261 | +>>> add = lambda x, y: x + y |
| 262 | +>>> add(5, 3) |
| 263 | +8 |
| 264 | +``` |
| 265 | +You could declare the same add function with the def keyword, but it would be slightly more verbose: |
| 266 | +```python |
| 267 | +def add(x, y): |
| 268 | + return x + y |
| 269 | +>>> add(5, 3) |
| 270 | +8 |
| 271 | +``` |
| 272 | + |
230 | 273 | ## Data Structures
|
231 | 274 |
|
232 | 275 | ### Lists
|
|
0 commit comments