We also covered Namespaces and Scope this week. Basically, when an object is created, the name assigned to that object is only valid in the namespace in which it was created. For example, say we create a variable x within a function test(). Variable x can be used anywhere inside the scope of function test(), but outside of that function, x does not exist. As a matter of fact, the outside of test() can have its own variable called x, which is completely independent of the x in test().
There are multiple levels of scopes that Python handles, from innermost to outermost:
- The local scope, which is the "current" function
- The nonlocal scope, which is the outer functions, if any, of a function.
- The global scope, which is the module, __main__
- The outermost scope, which has all of Python's built-in names.
No comments:
Post a Comment