Skip to main content
 首页 » 编程设计

Python 3 : Functions dependent on other functions, 缺少参数

2025年05月04日13yxwkf

我有两个函数,后者依赖于第一个函数的结果。 它们都是使用 float 的数学函数。

这两个函数的要点是:

def function1(a,aa,b,bb): 
    # get result z from a and b 
    # get error in result, zz, from raw errors, aa and bb 
    print (z,zz) 
 
def function2(z,zz,c,cc): 
    # get result x from z and c 
    # get error in result, xx, from zz and cc 
    print (x,xx) 

a、b 和 c 是在函数外部定义的测量变量 其中aa、bb、c为被测变量的误差,也在函数外定义。

定义函数后,我编写以下命令:

function2(function1(a,aa,b,bb),c,cc) 

我希望 function1 会产生两个结果 (z, zz),并且它们会被接受为 function2 的前两个参数。

相反,我收到错误“TypeError: function2() missing 1 required positional argument: 'cc'

所以我假设 function1 最后只产生一个结果。我该如何解决这个问题?

完整代码在这里:http://tinyurl.com/sof-typeerror

请您参考如下方法:

如果您的函数返回超过 1 个参数,那么这些参数将被打包到一个元组中。您应该解压用 * 返回的参数,以将它们作为参数传递给其他函数。但是,作为惯例,您不能将任何内容作为第一个参数解压缩,因此,我宁愿建议以下内容。

function2( *(function1(a,aa,b,bb) + (c, cc)) ) # would work 
 
function2(*function1(a,aa,b,bb),c,cc)          # won't work 

如果您真的对为什么后者不起作用或为什么约定感兴趣,请访问 - http://www.python.org/dev/peps/pep-3132/或 Unpacking arguments: only named arguments may follow *expression

此外,正如评论中所建议的那样,您应该返回参数而不只是打印它们。如下所示。

def function1(a,aa,b,bb): 
    get result z from a and b 
    get error in result, zz, from raw errors, aa and bb 
    print (z,zz) 
    return z, zz 
 
def function2(z,zz,c,cc): 
    get result x from z and c 
    get error in result, xx, from zz and cc 
    print (x,xx) 
    return x, xx