17 AnswersNew Answer
17 AnswersNew Answer
Frogged Instead of changing the values of the variables 's' and 'f', new variables local to b() and c() named 's' & 'f' are being created. I'm not sure about this part, but I think that Python thinks in the right-hand-side of `f, s = s, f` we are referencing the local variables 's' and 'f'. This is because changing 'f' and 's' to any other name works `a, b = f, s` I don't think there is any way to mutate the 'f' and 's' variables of the a() function without making them global. But maybe someone else can suggest a way? My suggestion is to make a list instead of the variables, like so lst = [True, False] And then replace every 's' with lst and 'f' with lst
Frogged yep , similar to how you can set attributes of classes and objects, you can also set attributes to functions. Useful when you want the option to retrieve some variable, but not explicity return it with the return statement. Also attributes can be set from inside the function definition or from outside the function definition.
XXX yes.. I think, Python is not clean here.... Finally : in a python closure all variables that are shared and changed by inner functions should be put into a mutable container. or..Vitaly Sokol thanks.. alternatively each one is to be marked as non-local
It is to understand closures
because of namespaces. you cant reference a variable inside a function without either passing the variable to the function or making the variable global
? its still a function. works the same no matter the scope. you added a function inside of another functions scope, the variables still need to be passed just like if you created to variables and made a function. you need to pass them or make them global
that goes with every variable
why wouldn't you just use a chain of elifs?
also you can do it with function attributes: https://code.sololearn.com/chMKa1VykhF0/?ref=app
Vitaly Sokol that's great
Calvin Thomas they are declared in the outer function. not globally. that's a point in closures: Although the outer function is no more in the memory, its variables are accessible and can be shared by the functions created and returned from outer function.
@slick but it is a closure no prob for accessing i
How about i
But I have access
Why doesn't "global f, s" work here? Am I not making f and s global variables?
Frogged I see, thanks for the explanation.
Sololearn Inc.4 Embarcadero Center, Suite 1455
Send us a message