This is an example of closures ( closure en English) and how they work.
When you define the function crear_area
, you are creating a local variable to that function named pi
and with default value pi
(global):
def crear_area(pi = pi):
Now, within that function, you are defining a second function area
that is returned as result / object:
pi = 3.14
def crear_area(pi = pi):
def area(r):
return pi*r*r
return area
As the scope ( scope in English) of area
is exclusively within crear_area
and its variables, it does not matter that you change the value of the global variable pi
, because area
will always use the local variable pi
of crear_area
that had a value of 3.14 at the time of its definition.
And that is the reason why, even if you change the value of pi
(global), print(area(10))
will always return the same: the internal variables maintain their value within the closure.
If you want them to have different values, then you would have to create a new area
by passing pi
as a parameter (so you would not use the default value but the new one you pass):
pi = 3.14
def crear_area(pi = pi):
def area(r):
return pi*r*r
return area
area = crear_area()
print(area(10)) #valor de retorno es 314.0
pi = 3 #referencia a Futurama
area = crear_area(pi)
print(area(10)) #valor de retorno es 300
In this way you would be creating a new environment with new variables and the values would be "reset" for area
.
Another possible alternative would be to not define the local variable pi
and so the global one would always be used, obtaining different values:
pi = 3.14
def crear_area():
def area(r):
return pi*r*r #ahora este pi es la variable global
return area
area = crear_area()
print(area(10)) #valor de retorno es 314.0
pi = 3 #referencia a Futurama
print(area(10)) #valor de retorno es 300