Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

Is it possible to change a function's default parameters in Python?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...