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.

>>> c.foo # bound method object<br />

>> c # instance foo()'s bound to<br />

<br />

14.1.3. Classes<br />

The callable property of classes allows instances to be created. "Invoking" a class has the effect of<br />

creating an instance, better known as instantiation. Classes have default constructors that perform no<br />

action, basically consisting of a pass statement. The programmer may choose to customize the<br />

instantiation process by implementing an __init__() method. Any arguments to an instantiation call are<br />

passed on to the constructor:<br />

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

def__init__(self, *args):<br />

print'Instantiated with these arguments:\n', args<br />

>>> c1 = C() # invoking class to instantiate c1<br />

Instantiated with these arguments:<br />

()<br />

>>> c2 = C('The number of the counting shall be', 3)<br />

Instantiated with these arguments:<br />

('The number of the counting shall be', 3)<br />

We are already familiar with the instantiation process and how it is accomplished, so we will keep this<br />

section brief. What is new, however, is how to make instances callable.<br />

14.1.4. Class Instances<br />

<strong>Python</strong> provides the __call__() special method for classes, which allows a programmer to create objects<br />

(instances) that are callable. By default, the __call__() method is not implemented, meaning that most<br />

instances are not callable. However, if this method is overridden in a class definition, instances of such a<br />

class are made callable. Calling such instance objects is equivalent to invoking the __call__() method.<br />

Naturally, any arguments given in the instance call are passed as arguments to __call__().<br />

You also have to keep in mind that __call__() is still a method, so the instance object itself is passed in<br />

as the first argument to __call__() as self. In other words, if foo is an instance, then foo() has the<br />

same effect as foo.__call__(foo)the occurrence of foo as an argumentsimply the reference to self that<br />

is automatically part of every method call. If __call__() has arguments, i.e., __call__(self,arg), then<br />

foo(arg) is the same as invoking foo.__call__(foo,arg). Here we present an example of a callable<br />

instance, using a similar example as in the previous section:<br />

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

... def __call__(self, *args):<br />

... print "I'm callable! Called with args:\n", args<br />

...<br />

>>> c = C() # instantiation<br />

>>> c # our instance<br />

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

Saved successfully!

Ooh no, something went wrong!