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.

def method(self, arg):"I am: spam.method.__doc__ or self.method._ _doc_ _"passdef func(args):"I am: docstr.func._ _doc_ _"passWhy You Will Care: Bound Methods and CallbacksBecause bound methods automatically pair an instance with a class method function,you can use them anywhere a simple function is expected. One of the most commonplaces you’ll see this idea put to work is in code that registers methods as event callbackhandlers in the Tkinter GUI interface. Here’s the simple case:def handler( ):...use globals for state......widget = Button(text='spam', command=handler)To register a handler for button click events, we usually pass a callable object that takesno arguments to the command keyword argument. Function names (and lambdas) workhere, and so do class methods, as long as they are bound methods:class MyWidget:def handler(self):...use self.attr for state...def makewidgets(self):b = Button(text='spam', command=self.handler)Here, the event handler is self.handler—a bound method object that remembers bothself and MyGui.handler. Because self will refer to the original instance when handleris later invoked on events, the method will have access to instance attributes that canretain state between events. With simple functions, state normally must be retained inglobal variables instead. See also the discussion of _ _call_ _ operator overloading inChapter 24 for another way to make classes compatible with function-based AP<strong>Is</strong>.The main advantage of documentation strings is that they stick around at runtime.Thus, if it’s been coded as a docstring, you can qualify an object with its _ _doc_ _attribute to fetch its documentation:>>> import docstr>>> docstr._ _doc_ _'I am: docstr._ _doc_ _'>>> docstr.spam._ _doc_ _'I am: spam.__doc__ or docstr.spam._ _doc_ _'>>> docstr.spam.method._ _doc_ _'I am: spam.method.__doc__ or self.method._ _doc_ _'536 | Chapter 25: Designing with Classes

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

Saved successfully!

Ooh no, something went wrong!