12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Namespaces: The Whole StoryNow that we’ve examined class and instance objects, the <strong>Python</strong> namespace story iscomplete. For reference, I’ll quickly summarize all the rules used to resolve nameshere. The first things you need to remember are that qualified and unqualified namesare treated differently, and that some scopes serve to initialize object namespaces:• Unqualified names (e.g., X) deal with scopes.• Qualified attribute names (e.g., object.X) use object namespaces.• Some scopes initialize object namespaces (for modules and classes).Simple Names: Global Unless AssignedUnqualified simple names follow the LEGB lexical scoping rule outlined for functionsin Chapter 16:Assignment (X= value)Makes names local: creates or changes the name X in the current local scope,unless declared global.Reference (X)Looks for the name X in the current local scope, then any and all enclosing functions,then the current global scope, then the built-in scope.Attribute Names: Object NamespacesQualified attribute names refer to attributes of specific objects, and obey the rules formodules and classes. For class and instance objects, the reference rules are augmentedto include the inheritance search procedure:Assignment (object.X= value)Creates or alters the attribute name X in the namespace of the object being qualified,and none other. Inheritance-tree climbing happens only on attributereference, not on attribute assignment.Reference (object.X)For class-based objects, searches for the attribute name X in object, then in allaccessible classes above it, using the inheritance search procedure. For nonclassobjects such as modules, fetches X from object directly.The “Zen” of <strong>Python</strong> Namespaces: Assignments Classify NamesWith distinct search procedures for qualified and unqualified names, and multiplelookup layers for both, it can sometimes be difficult to tell where a name will wind upgoing. In <strong>Python</strong>, the place where you assign a name is crucial—it fully determines thescope or object in which a name will reside. The file manynames.py illustrates how this506 | Chapter 24: Class Coding Details

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!