简体   繁体   English

Python - 在其他函数中传递带参数的函数作为参数

[英]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. 问题是,用户可以使用他们想要的任何“k”值调用“anotherFunc”,这会使事情复杂化。 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? 或者我有什么方法可以根据之前的功能设置多个默认值'k',同时仍允许用户根据需要选择自己的'k'?

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. foo在定义函数时充当第一个函数参数的占位符。 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)
     ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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