Inner Functions
In this lesson, you’ll see how to define Python functions inside of other functions.
00:00
Next, I want to show you inner functions. Is it possible to define functions inside of other functions? Sure! Let me show you an example. To start, I’ll have you define a function named parent()
.
00:17
The first part of the statement, parent()
is going to print("Printing from the parent() function")
. Next, you need to indent over and define another function inside of parent()
.
00:28
It’s named first_child()
. So far, all of these functions don’t take any arguments. I made a small mistake there, pressing Return a little early, but it will work the same. So for this function, first_child()
, it will have a print statement saying "Printing from the first_child() function"
.
00:48
And now I’ll have you define a second_child()
function. It will look similar, "Printing from the second_child()"
. Now, before you leave the statement and end this function, I’ll have you call second_child()
with parentheses—so we’ll call it—and then call first_child()
.
01:06
So, what will happen when you call parent()
? First off, as it walks down through the statement, it prints "the parent() function"
.
01:17
Then it defines first_child()
and defines second_child()
, setting both of them up. Then, it actually will print "the second_child() function"
, and print "the first_child() function"
last. I know this is a very simple example, but you can get the concept that even elaborate functions could be defined inside of other functions.
01:42
What if you tried to access first_child
by typing its name? It says […] 'first_child' is not defined
. And second_child
?
01:56 Same thing. So those objects are not defined within the scope outside of this function.
02:05
They’re only inside parent()
.
02:10 Both of them reside inside of there, locally. That’s what the next video is about. What if you wanted to access functions that live inside another function?
02:22 Can you return them out of an existing parent function? Get them out of the local scope, and be usable outside of it? That’s what I’ll show you next.
bmcnaspy on July 17, 2024
All of this is well and good, but you go about this as if I would know what to choose and how to implement it. I follow the paths you are creating, but I know DOS and this is much like it. However, the way you are doing things, like the def
and the _()
, they are being used in ways I haven’t learned. I may need some type of starter course on what is what and why it is used the way you do, because it is getting thick already and I haven’t even scratched the surface. Thanks.
Become a Member to join the conversation.
dwalsh on June 9, 2020
So functions can be incepted.