Reputation: 4155
If I have two functions, (one inside the other);
def test1():
def test2():
print("test2")
How do I call test2
?
Upvotes: 1
Views: 188
Reputation: 769
You can call it in this way too:
def test1():
text = "Foo is pretty"
print "Inside test1()"
def test2():
print "Inside test2()"
print "test2() -> ", text
return test2
test1()() # first way, prints "Foo is pretty"
test2 = test1() # second way
test2() # prints "Foo is pretty"
Let's see:
>>> Inside test1()
>>> Inside test2()
>>> test2() -> Foo is pretty
>>> Inside test1()
>>> Inside test2()
>>> test2() -> Foo is pretty
If you don't want to call the test2()
:
test1() # first way, prints "Inside test1()", but there's test2() as return value.
>>> Inside test1()
print test1()
>>> <function test2 at 0x1202c80>
Let's get more hard:
def test1():
print "Inside test1()"
def test2():
print "Inside test2()"
def test3():
print "Inside test3()"
return "Foo is pretty."
return test3
return test2
print test1()()() # first way, prints the return string "Foo is pretty."
test2 = test1() # second way
test3 = test2()
print test3() # prints "Foo is pretty."
Let's see:
>>> Inside test1()
>>> Inside test2()
>>> Inside test3()
>>> Foo is pretty.
>>> Inside test1()
>>> Inside test2()
>>> Inside test3()
>>> Foo is pretty.
Upvotes: 3
Reputation: 799370
You can't, since test2
stops existing once test1()
has returned. Either return it from the outer function or only ever call it from there.
Upvotes: 0
Reputation: 460
def test1():
def test2():
print "Here!"
test2() #You need to call the function the usual way
test1() #Prints "Here!"
Note that the test2
function is not available outside of test1
. If, for instance, you tried to call test2()
later in your code, you would get an error.
Upvotes: 3