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.

class Prod:... def _ _init_ _(self, value):... self.value = value... def _ _call_ _(self, other):... return self.value * other...>>> x = Prod(2)>>> x(3)6>>> x(4)8In this example, the _ _call_ _ may seem a bit gratuitous. A simple method providessimilar utility:>>> class Prod:... def _ _init_ _(self, value):... self.value = value... def comp(self, other):... return self.value * other...>>> x = Prod(3)>>> x.comp(3)9>>> x.comp(4)12However, _ _call_ _ can become more useful when interfacing with AP<strong>Is</strong> that expectfunctions—it allows us to code objects that conform to an expected function callinterface, but also retain state information. In fact, it’s probably the third most commonlyused operator overloading method, behind the _ _init_ _ constructor, and the_ _str_ _ and _ _repr_ _ display-format alternatives.Function Interfaces and Callback-Based CodeAs an example, the Tkinter GUI toolkit, which we’ll meet later in this book, allowsyou to register functions as event handlers (a.k.a. callbacks); when events occur,Tkinter calls the registered objects. If you want an event handler to retain statebetween events, you can register either a class’ bound method, or an instance thatconforms to the expected interface with _ _call_ _. In this section’s code, both x.compfrom the second example, and x from the first, can pass as function-like objects thisway.I’ll have more to say about bound methods in the next chapter, but for now, here’s ahypothetical example of _ _call_ _ applied to the GUI domain. The following classdefines an object that supports a function-call interface, but also has state informationthat remembers the color a button should change to when it is later pressed:class Callback:def _ _init_ _(self, color):self.color = colordef _ _call_ _(self):print 'turn', self.color# Function + state information# Support calls with no argumentsOperator Overloading | 503

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

Saved successfully!

Ooh no, something went wrong!