Python Cookbook question re 5.6

Scott David Daniels Scott.Daniels at Acm.Org
Mon Dec 15 11:51:07 EST 2003


Joe wrote:
> The recipe in question is "Implementing Static Methods".  It shows how to
> use staticmethod().  This sentence in the Discussion section isn't clear to
> me:  "An attribute of a class object that starts out as a Python function
> implicitly mutates into an unbound method."  I'm not sure what this means,
> exactly.  Can anyone elaborate?
> 
> Thanks,
> Chris

First, you might cite the actual recipe here, so people can go look:


The way a class is constructed consists of:
  1) open a scope at the point where the class definition starts.
  2) Collect each definition in the scope (value an name).  At this
     point (during the collection), you are building "normal"
     functions with def.
  3) When the end of the class definition is found, all of the
     definitions collected in (2), along with the class name and
     superclasses are used to build the actual class.  This is the
     moment when the normal functions created in step 2 are used
     to build "unbound methods" -- the magic used to make objects
     work.

Here's some code that, once you understand it, illustrates this:

     class SomeClass(object):
         def function(self, other):
             print 'called with self=%s, and other =%s' % (self, other)
             return self, other

         pair = function(1,2)  # normal during class construction
         print pair            # We can even see the pair.
         statmeth = staticmethod(function)# uses, not changes, function
         pair2 = function(2,3) # Demonstrate function still works

     print SomeClass.pair, SomeClass.pair2 # The class vars are there
     obj = SomeClass()         # make an instance
     pair3 = obj.function(4)   # Note only 1 arg is accepted.
     print obj, pair3          # the object was used as the first arg
     pair4 = SomeClass.statmeth(4, 5)  # The old function behavior
     pair5 = obj.statmeth(5, 6)# Also the old function behavior

     pair6 = SomeClass.function(obj, 7) # An "unbound method" can
                                # be used on the right kind of object
     pair7 = SomeClass.function(7, 8) # Raises an exception!  An
                                # "unbound method" needs the correct
                                # kind of object as its first argument.

-Scott David Daniels
Scott.Daniels at Acm.Org




More information about the Python-list mailing list