15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

In keeping with OOP tradition, <strong>Python</strong> imposes the restriction that methods cannot be invoked without<br />

instances. An instance must be used to perform method calls. This restriction describes <strong>Python</strong>'s concept<br />

of binding, where methods must be bound (to an instance) in order to be invoked directly. Unbound<br />

methods may also be called, but an instance object must be provided explicitly in order for the<br />

invocation to succeed. However, regardless of binding, methods are inherently attributes of the class<br />

they are defined in, even if they are almost always invoked via an instance. We will further explore<br />

bound and unbound methods later in Section 13.7.<br />

13.4.3. Determining Class Attributes<br />

There are two ways to determine what attributes a class has. The simplest way is to use the dir() builtin<br />

function. An alternative is to access the class dictionary attribute __dict__, one of a number of special<br />

attributes that is common to all classes. Let us take a look at an example:<br />

>>> class MyClass(object):<br />

... 'MyClass class definition'<br />

... myVersion = '1.1' # static data<br />

... def showMyVersion(self): # method<br />

... print MyClass.myVersion<br />

...<br />

Using the class defined above, let us use dir() and the special class attribute __dict__ to see this class's<br />

attributes:<br />

>>> dir(MyClass)<br />

['__class__', '__delattr__', '__dict__', '__doc__',<br />

'__getattribute__', '__hash__', '__init__', '__module__',<br />

'__new__', '__reduce__', '__reduce_ex__', '__repr__',<br />

'__setattr__', '__str__', '__weakref__', 'myVersion',<br />

'showMyVersion']<br />

>>> MyClass.__dict__<br />

<br />

>>> print MyClass.__dict__<br />

{'showMyVersion': ,<br />

'__dict__': ,<br />

'myVersion': '1.1', '__weakref__': , '__doc__':<br />

'MyClass class definition'}<br />

There are a few more attributes added for new-style classes as well as a more robust dir() function.<br />

Just for comparison, here is what you would see for classic classes:<br />

>>> dir(MyClass)<br />

['__doc__', '__module__', 'showMyVersion', 'myVersion']<br />

>>><br />

>>> MyClass.__dict__<br />

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

, '__module__':<br />

'__main__'}

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

Saved successfully!

Ooh no, something went wrong!