12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

principle translates to code, and summarizes the namespace ideas we have seenthroughout this book:# manynames.pyX = 11# Global (module) name/attribute (X, or manynames.X)def f( ):print X # Access global X (11)def g( ):X = 22 # Local (function) variable (X, hides module X)print Xclass C:X = 33def m(self):X = 44self.X = 55# Class attribute (C.X)# Local variable in method (X)# Instance attribute (instance.X)This file assigns the same name, X, five times. Because this name is assigned in fivedifferent locations, though, all five Xs in this program are completely different variables.From top to bottom, the assignments to X here generate: a module attribute(11), a local variable in a function (22), a class attribute (33), a local variable in amethod (44), and an instance attribute (55). Although all five are named X, the factthat they are all assigned at different places in the source code or to different objectsmakes all of these unique variables.You should take the time to study this example carefully because it collects ideaswe’ve been exploring throughout the last few parts of this book. When it makessense to you, you will have achieved a sort of <strong>Python</strong> namespace nirvana. Of course,an alternative route to nirvana is to simply run the program and see what happens.Here’s the remainder of this source file, which makes an instance, and prints all theXs that it can fetch:# manynames.py, continuedif __name__ == '_ _main_ _':print X# 11: module (a.k.a. manynames.X outside file)f( ) # 11: globalg( ) # 22: localprint X# 11: module name unchangedobj = C( )print obj.Xobj.m( )print obj.Xprint C.X#print c.m.X#print f.X# Make instance# 33: class name inherited by instance# Attach attribute name X to instance now# 55: instance# 33: class (a.k.a. obj.X if no X in instance)# FAILS: only visible in method# FAILS: only visible in functionNamespaces: The Whole Story | 507

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

Saved successfully!

Ooh no, something went wrong!