Nested Methods:
- Defining a method inside another method.
- We cannot access nested method from outside.
def outer():
print("outer method")
def inner():
print("inner method")
return
return
outer()
inner() # error
We access nested method from the definition of outer() method.
def outer():
print("outer method")
def inner():
print("inner method")
return
inner()
return
outer()
Local and Non local variables in nested methods:
- Local variables are defined inside the inner function.
- Outer function variables are called non local variables of inner function.
- When we access a variable inside the nested function, it gives the priority to nested function only.
def outer():
x=10
print("outer x : ",x)
def inner():
x=20
print("inner x : ",x)
return
inner()
return
outer()
Non variables are nothing but, accessing outer() method variables inside inner() method when local variable is not present inside inner method.
def outer():
x=10
print("outer x : ",x)
def inner():
print("inner x : ",x)
return
inner()
return
outer()
- Arguments are working like local variables of function.
- Outer() method arguments working like non local variables of nested method.
def outer(x):
print("outer x : ",x)
def inner():
print("inner x : ",x)
return
inner()
return
outer(50)