What are Python namespaces all about

前端 未结 6 1247
抹茶落季
抹茶落季 2020-11-30 23:14

I have just started learning Python & have come across \"namespaces\" concept in Python. While I got the jist of what it is, but am unable to appreciate

6条回答
  •  死守一世寂寞
    2020-12-01 00:11

    Namespace is a way to implement scope.

    In Java (or C) the compiler determines where a variable is visible through static scope analysis.

    • In C, scope is either the body of a function or it's global or it's external. The compiler reasons this out for you and resolves each variable name based on scope rules. External names are resolved by the linker after all the modules are compiled.

    • In Java, scope is the body of a method function, or all the methods of a class. Some class names have a module-level scope, also. Again, the compiler figures this out at compile time and resolves each name based on the scope rules.

    In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. Plus there's a global namespace that's used if the name isn't in the local namespace.

    Each variable name is checked in the local namespace (the body of the function, the module, etc.), and then checked in the global namespace.

    Variables are generally created only in a local namespace. The global and nonlocal statements can create variables in other than the local namespace.

    When a function, method function, module or package is evaluated (that is, starts execution) a namespace is created. Think of it as an "evaluation context". When a function or method function, etc., finishes execution, the namespace is dropped. The variables are dropped. The objects may be dropped, also.

提交回复
热议问题