简体   繁体   中英

passing same argument from outer function to inner function in python

I have a inner function function

def inner_function(scenario = 'name',myopic_variable = True):

    if scenario == 'name':
        print('Name')

    if myopic_variable == True:
        print('Myopic is True')

and the main function like this.

def main_function(scenario = 'name',myopic_variable = True):
    inner_function()

Now when I am calling main function like this it works fine

main_function(scenario = 'name',myopic_variable = True)

but when i change myopic_variable = False it still gives me the same output why?

def inner_function(scenario = 'name',myopic_variable = True): You are passing a default value of true here.

def main_function(scenario = 'name',myopic_variable = True):
    inner_function()

Here, no parameters are passed to inner_functions() , it prints True , the default value. To make it correct, call inner_function(myopic_variable = myopic_variable)

Well that's because you are using something called default arguments in python. To understand what you are facing, let's take an example:

def inner_fun(a=True):
     print(a)

inner_fun() 

will print True because we are not passing any argument while calling this function. It will thus takr the default argument which is True here.

If you run inner_fun(False) , it'll print False because this time you are passing an argument in the function which has higher precedence than the default value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM