12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

On the other hand, if we qualify the class to get to doit, we get back an unboundmethod object, which is simply a reference to the function object. To call this type ofmethod, we must pass in an instance as the leftmost argument:object1 = Spam( )t = Spam.doitt(object1, 'howdy')# Unbound method object# Pass in instanceBy extension, the same rules apply within a class’ method if we reference selfattributes that refer to functions in the class. A self.method expression is a boundmethod object because self is an instance object:class Eggs:def m1(self, n):print ndef m2(self):x = self.m1x(42)Eggs( ).m2( ) # Prints 42# Another bound method object# Looks like a simple functionMost of the time, you call methods immediately after fetching them with qualification,so you don’t always notice the method objects generated along the way. But ifyou start writing code that calls objects generically, you need to be careful to treatunbound methods specially—they normally require an explicit instance object to bepassed in. *Now that you understand the method object model, for other examples of boundmethods at work, see this chapter’s sidebar “Why You Will Care: Bound Methodsand Callbacks,” and the prior chapter’s discussion of callback handlers in the section“_ _call_ _ Intercepts Calls.”Documentation Strings RevisitedDocstrings, which we covered in detail in Chapter 14, are string literals that show upat the top of various structures, and are automatically saved by <strong>Python</strong> in the correspondingobjects’ _ _doc_ _ attributes. This works for module files, function defs, andclasses and methods. Now that we know more about classes and methods, the filedocstr.py provides a quick but comprehensive example that summarizes the placeswhere docstrings can show up in your code. All of these can be triple-quoted blocks:"I am: docstr._ _doc_ _"class spam:"I am: spam.__doc__ or docstr.spam._ _doc_ _"* See the discussion of static and class methods in Chapter 26 for an optional exception to this rule. Likebound methods, both of these can masquerade as basic functions, too, because they do not expect instanceswhen called.Documentation Strings Revisited | 535

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

Saved successfully!

Ooh no, something went wrong!