15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

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

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

As you can tell, dir() returns a list of (just the) names of an object's attributes while __dict__ is a<br />

dictionary whose attribute names are the keys and whose values are the data values of the<br />

corresponding attribute objects.<br />

The output also reveals two familiar attributes of our class MyClass, showMyVersion and myVersion, as well<br />

as a couple of new ones. These attributes, __doc__ and __module__, are special class attributes that all<br />

classes have (in addition to __dict__). The vars() built-in function returns the contents of a class's<br />

__dict__ attribute when passed the class object as its argument.<br />

13.4.4. Special Class Attributes<br />

For any class C, Table 13.1 represents a list of all the special attributes of C:<br />

Table 13.1. Special Class Attributes<br />

C.__name__ String name of class C<br />

C.__doc__ Documentation string for class C<br />

C.__bases__ Tuple of class C's parent classes<br />

C.__dict__ Attributes of C<br />

C.__module__ Module where C is defined (new in 1.5)<br />

C.__class__ Class of which C is an instance (new-style classes only)<br />

Using the class MyClass we just defined above, we have the following:<br />

>>> MyClass.__name__<br />

'MyClass'<br />

>>> MyClass.__doc__<br />

'MyClass class definition'<br />

>>> MyClass.__bases__<br />

(,)<br />

>>> print MyClass.__dict__<br />

{'__doc__': None, 'myVersion': 1, 'showMyVersion':<br />

, '__module__': '__main__'}<br />

>>> MyClass.__module__<br />

'__main__'<br />

>>> MyClass.__class__<br />

<br />

__name__ is the string name for a given class. This may come in handy in cases where a string is desired<br />

rather than a class object. Even some built-in types have this attribute, and we will use one of them to<br />

showcase the usefulness of the __name__ string.<br />

The type object is an example of one built-in type that has a __name__ attribute. Recall that type()

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

Saved successfully!

Ooh no, something went wrong!