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.

To help you understand how attributes work internally, let’s work through an interactivesession that traces the way namespace dictionaries grow when classes areinvolved. First, let’s define a superclass and a subclass with methods that will storedata in their instances:>>> class super:... def hello(self):... self.data1 = 'spam'...>>> class sub(super):... def hola(self):... self.data2 = 'eggs'...When we make an instance of the subclass, the instance starts out with an emptynamespace dictionary, but has links back to the class for the inheritance search to follow.In fact, the inheritance tree is explicitly available in special attributes, which youcan inspect. Instances have a _ _class_ _ attribute that links to their class, and classeshave a _ _bases_ _ attribute that is a tuple containing links to higher superclasses:>>> X = sub( )>>> X._ _dict_ _{ }>>> X._ _class_ _>>> sub._ _bases_ _(,)>>> super._ _bases_ _()As classes assign to self attributes, they populate the instance objects—that is,attributes wind up in the instances’ attribute namespace dictionaries, not in theclasses’. An instance object’s namespace records data that can vary from instance toinstance, and self is a hook into that namespace:>>> Y = sub( )>>> X.hello( )>>> X._ _dict_ _{'data1': 'spam'}>>> X.hola( )>>> X._ _dict_ _{'data1': 'spam', 'data2': 'eggs'}>>> sub._ _dict_ _{'_ _module_ _': '_ _main_ _', '_ _doc_ _': None, 'hola': }Namespaces: The Whole Story | 509

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

Saved successfully!

Ooh no, something went wrong!