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.

The outputs that are printed when the file is run are noted in the comments in thecode; trace through them to see which variable named X is being accessed each time.Notice in particular that we can go through the class to fetch its attribute (C.X), butwe can never fetch local variables in functions, or methods from outside their defstatements. Locals are only visible to other code within the def, and, in fact, only livein memory while a call to the function or method is executing.Some of the names defined by this file are visible outside the file to other modules,but recall that we must always import before we can access names in another file—that is the main point of modules, after all:# otherfile.pyimport manynamesX = 66print Xprint manynames.Xmanynames.f( )manynames.g( )# 66: the global here# 11: globals become attributes after imports# 11: manynames's X, not the one here!# 22: local in other file's functionprint manynames.C.XI = manynames.C( )print I.XI.m( )print I.X508 | Chapter 24: Class Coding Details# 33: attribute of class in other module# 33: still from class here# 55: now from instance!Notice here how manynames.f( ) prints the X in manynames, not the X assigned in thisfile—scopes are always determined by the position of assignments in your sourcecode (i.e., lexically), and are never influenced by what imports what, or who importswhom. Also, notice that the instance’s own X is not created until we call I.m( )—attributes, like all variables, spring into existence when assigned, and not before.Normally we create instance attributes by assigning them in class _ _init_ _ constructormethods, but this isn’t the only option.You generally shouldn’t use the same name for every variable in your script, ofcourse! But as this example demonstrates, even if you do, <strong>Python</strong>’s namespaces willwork to keep names used in one context from accidentally clashing with those usedin another.Namespace DictionariesIn Chapter 19, we learned that module namespaces are actually implemented as dictionaries,and exposed with the built-in _ _dict_ _ attribute. The same holds for classand instance objects: attribute qualification is really a dictionary indexing operationinternally, and attribute inheritance is just a matter of searching linked dictionaries.In fact, instance and class objects are mostly just dictionaries with links inside<strong>Python</strong>. <strong>Python</strong> exposes these dictionaries, as well as the links between them, for usein advanced roles (e.g., for coding tools).

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

Saved successfully!

Ooh no, something went wrong!