I am a C programmer who is learning Python. Recently I have been being confused by the rules of scope and namespace in nested functions within a certain class.
Example Code:
Class CLASS_A:
def FUNCTION_A(argument a, ..., argument n):
max = 0
visit = set()
def FUNCTION_B(argument a, ..., argument n):
visit.add(...)
frequency = ....
nonlocal max
max = ... if ... frequency ... max ... else ...
return
FUNCTION_B(...)
return max
In the example code, both "max" and "visit" are declared(?) and initialised in the outer(?) function FUNCTION_A. Therefore, so as to get access and modify the value of "max" within its own scope, FUNCTION_B must execute a non-local statement before trying to do so.
However, the same situation does not apply to "visit", a set, we can just modify its value directly as if it was declared in the FUNCTION_B itself.
I have noticed that when it comes to array, set, dictionary, etc. (all of them are classes in Python?), we don't need to give much extra care regarding the scope and namespace. We only need a non-local or global statement when we try to modify a variable like integer.
What's the underlying reason of such differences?