There are four areas here:
- global area
- scope
- class body
- lambda area
When creating a class operator, the class body is executed as a function, and the local namespace of this function is used as class attributes.
However, the body of the class is not a scope and, as a result, behaves differently than functions. In the body of a function, a binding defines an area; assign a name to the function and it is marked as local. In a class, assigning a name makes it global until you actually complete the task.
So, your first call to print() finds my_str as global, because later in the class of the class you are bound to a name. This is a consequence of the fact that class bodies do not participate in regions.
Then you define the lambda and call it. my_str never assigned in this lambda, so it needs to be found in the parent scope. Here, the class body is not a scope, and the next scope is the scope. This is why this line prints inside func .
Finally, you assign the local name my_str in the body of the class and print this local.
At the time the assignment is deleted, names in the class are considered non-local; the first and last print() statements are now equal, and the name is simply looked up according to the usual scope rules.
source share