Pergunta

Hope I doesn't repeat any question, but couldn't find...

I'm trying to run a function with the same key parameter many times. I understand why the f function changes the x0 array, but I don't really understand why the g function takes every time different argument (y0 is constant). I would be thankful if anyone can explain me this behaviour and give me a tip how to implement what I want (basically at the end I would like to have y == np.array([0, 30, 0]) ).

import numpy as np

x0 = np.zeros(3)
y0 = np.zeros(3)

def f(i, x = x0):
    x[1] += i
    return x

def g(i, y = y0.copy()):
    print "y that goes to g (every time is different) \n", y
    y[1] += i
    return y

print "x0 before f \n" ,x0
x = f(5)
print "x0 after f is the same as x  \n", x0, "\n", x

print "y0 before g \n" ,y0
for i in [10, 20, 30]:
    y = g(i)
print "y0 after g doe not change, but y is NOT as I would expect! \n", y0, "\n", y
Foi útil?

Solução

Default arguments to functions are evaluated only once, when the function is defined. This means that your function definition is equivalent to:

y0_ = y0.copy()
def g(i, y = y0_):
    print "y that goes to g (every time is different) \n", y
    etc

Which explains why your y argument changes every time.

Outras dicas

"but I don't really understand why the g function takes every time different argument"

def g(i, y = y0.copy()):
    ....

Your y0 is constant but you are creating copy of y0 with different reference first time when g() function is called so you can't change y0 with function g(). Just change

y = y0.copy() 

to

y=y0
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top