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.

super._ _dict_ _{'_ _module_ _': '_ _main_ _', 'hello': ,'_ _doc_ _': None}>>> sub.__dict__.keys( ), super._ _dict_ _.keys( )(['_ _module_ _', '_ _doc_ _', 'hola'], ['_ _module_ _', 'hello', '_ _doc_ _'])>>> Y._ _dict_ _{ }Notice the extra underscore names in the class dictionaries; <strong>Python</strong> sets these automatically.Most are not used in typical programs, but there are tools that use some ofthem (e.g., _ _doc_ _ holds the docstrings discussed in Chapter 14).Also, observe that Y, a second instance made at the start of this series, still has anempty namespace dictionary at the end, even though X’s dictionary has been populatedby assignments in methods. Again, each instance has an independentnamespace dictionary, which starts out empty, and can record completely differentattributes than those recorded by the namespace dictionaries of other instances ofthe same class.Because attributes are actually dictionary keys inside <strong>Python</strong>, there are really twoways to fetch and assign their values—by qualification, or by key indexing:>>> X.data1, X._ _dict_ _['data1']('spam', 'spam')>>> X.data3 = 'toast'>>> X._ _dict_ _{'data1': 'spam', 'data3': 'toast', 'data2': 'eggs'}>>> X._ _dict_ _['data3'] = 'ham'>>> X.data3'ham'This equivalence applies only to attributes actually attached to the instance, though.Because attribute qualification also performs an inheritance search, it can accessattributes that namespace dictionary indexing cannot. The inherited attribute X.hello,for instance, cannot be accessed by X._ _dict_ _['hello'].Finally, here is the built-in dir function we met in Chapters 4 and 14 at work onclass and instance objects. This function works on anything with attributes:dir(object) is similar to an object._ _dict_ _.keys( ) call. Notice, though, that dirsorts its list and includes some system attributes—as of <strong>Python</strong> 2.2, dir also collectsinherited attributes automatically: ** The contents of attribute dictionaries and dir call results may change over time. For example, because<strong>Python</strong> now allows built-in types to be subclassed like classes, the contents of dir results for built-in typeshave expanded to include operator overloading methods. In general, attribute names with leading and trailingdouble underscores are interpreter-specific. Type subclasses will be discussed further in Chapter 26.510 | Chapter 24: Class Coding Details

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

Saved successfully!

Ooh no, something went wrong!