本文介绍了是否有可能在Python中更改函数的默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是否可以在运行时重新定义函数的默认参数?

我在这里定义了一个带有3个参数的函数:

  def multiplyNumbers(x,y,z):
return x * y * z

print(multiplyNumbers( x = 2,y = 3,z = 3))

接下来,我尝试(失败)设置y的默认参数值,然后我尝试调用不带参数 y 的函数:

  multiplyNumbers.y = 2; 
print(multiplyNumbers(x = 3,z = 3))

因为 y 的默认值没有被正确设置:

  TypeError:multiplyNumbers()缺少1所需的位置参数:'y'

是否有可能重新定义在运行时的默认参数,正如我在这里试图做的那样? 只需使用

  multiplyNumbers = functools.partial(multiplyNumbers,y = 42)

一问题在这里:你不能称之为 multiplyNumbers(5,7,9); 你应该手动说 y = 7 $ b

如果您需要删除默认参数,我会看到两种方式:


  1. 将原始功能存储在某处

      oldF = f 
    f = functools.partial(f,y = 42)
    //使用改变的功能f
    f = oldF //恢复


  2. 使用 partial.func $ b

      f = f.func //转到上一个版本。 



In Python, is it possible to redefine the default parameters of a function at runtime?

I defined a function with 3 parameters here:

def multiplyNumbers(x,y,z):
    return x*y*z

print(multiplyNumbers(x=2,y=3,z=3))

Next, I tried (unsuccessfully) to set the default parameter value for y, and then I tried calling the function without the parameter y:

multiplyNumbers.y = 2;
print(multiplyNumbers(x=3, z=3))

But the following error was produced, since the default value of y was not set correctly:

TypeError: multiplyNumbers() missing 1 required positional argument: 'y'

Is it possible to redefine the default parameters of a function at runtime, as I'm attempting to do here?

解决方案

Just use functools.partial

 multiplyNumbers = functools.partial(multiplyNumbers, y = 42)

One problem here: you will not be able to call it as multiplyNumbers(5, 7, 9); you should manually say y=7

If you need to remove default arguments I see two ways:

  1. Store original function somewhere

    oldF = f
    f = functools.partial(f, y = 42)
    //work with changed f
    f = oldF //restore
    

  2. use partial.func

    f = f.func //go to previous version.
    

这篇关于是否有可能在Python中更改函数的默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:09