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.

Methods Are Objects: Bound or UnboundMethods are a kind of object, much like functions. Class methods can be accessedfrom an instance or a class, and hence, they actually come in two flavors in <strong>Python</strong>:Unbound class method objects: no selfAccessing a function attribute of a class by qualifying a class returns an unboundmethod object. To call the method, you must provide an instance object explicitlyas the first argument.Bound instance method objects: self + function pairsAccessing a function attribute of a class by qualifying an instance returns abound method object. <strong>Python</strong> automatically packages the instance with thefunction in the bound method object, so you don’t need to pass an instance tocall the method.Both kinds of methods are full-fledged objects; they can be passed around, stored inlists, and so on. Both also require an instance in their first argument when run (i.e., avalue for self). This is why we had to pass in an instance explicitly when callingsuperclass methods from subclass methods in the previous chapter; technically, suchcalls produce unbound method objects.When calling a bound method object, <strong>Python</strong> provides an instance for you automatically—theinstance used to create the bound method object. This means that boundmethod objects are usually interchangeable with simple function objects, and makesthem especially useful for interfaces originally written for functions (see the sidebar“Why You Will Care: Bound Methods and Callbacks” for a realistic example).To illustrate, suppose we define the following class:class Spam:def doit(self, message):print messageNow, in normal operation, we make an instance, and call its method in a single stepto print the passed-in argument:object1 = Spam( )object1.doit('hello world')Really, though, a bound method object is generated along the way, just before themethod call’s parentheses. In fact, we can fetch a bound method without actuallycalling it. An object.name qualification is an object expression. In the following, itreturns a bound method object that packages the instance (object1) with the methodfunction (Spam.doit). We can assign this bound method to another name, and thencall it as though it were a simple function:object1 = Spam( )x = object1.doitx('hello world')# Bound method object: instance+function# Same effect as object1.doit('...')534 | Chapter 25: Designing with Classes

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

Saved successfully!

Ooh no, something went wrong!