简体   繁体   中英

Python - Passing Functions with Arguments as Arguments in other Functions

I'm new to programming and I've been stuck on this issue and would really like some help!

One of the parameters in my function is optional, but can take on multiple default values based on another function. Both functions take in the same input (among others). When I try to assign a default using the function as illustrated below:

def func(foo): 
    # returns different values of some variable k based on foo

def anotherFunc(foo, bar, k=func(foo)):
    # this is the same foo input as the previous function

I get the following error:

NameError: name 'foo' is not defined

The thing is, the user can call 'anotherFunc' with any value of 'k' they want, which complicates things. Is there any way to have a function with arguments in it as a parameter in another function? Or is there any way for me to set multiple default values of 'k' based on the previous function while still allowing the user to choose their own 'k' if they wanted?

Thanks!

You would probably want to do something like:

def func(foo):
    return foo

def anotherfunc(foo, bar, k=None):
    if k == None:
        k = func(foo)
    #process whatever

foo at the moment of defining the function acts as placeholder for the first function argument. It has no value until the function is called, for which its value can be accessed in the function body, like so:

def another_func(foo, bar, k=None):
     if k is None:
         k = func(foo)
     ...

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