Python Cookbook question re 5.6

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joe

    Python Cookbook question re 5.6

    The recipe in question is "Implementi ng 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



  • Scott David Daniels

    #2
    Re: Python Cookbook question re 5.6

    Joe wrote:[color=blue]
    > The recipe in question is "Implementi ng 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[/color]

    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(objec t):
    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(fu nction)# 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.statm eth(4, 5) # The old function behavior
    pair5 = obj.statmeth(5, 6)# Also the old function behavior

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

    -Scott David Daniels
    Scott.Daniels@A cm.Org

    Comment

    • Sean Ross

      #3
      Re: Python Cookbook question re 5.6


      "Joe" <freak@yeah.com > wrote in message
      news:SX%Cb.5486 24$Fm2.517912@a ttbi_s04...[color=blue]
      > The recipe in question is "Implementi ng Static Methods". It shows how to
      > use staticmethod(). This sentence in the Discussion section isn't clear[/color]
      to[color=blue]
      > 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
      >[/color]

      Here's an example that may help show what's going on:

      class C:
      def f():
      print "f"
      print type(f)

      print type(C.f)
      try:
      C.f()
      except TypeError, e:
      print e
      try:
      c = C()
      C.f(c)
      except TypeError, e:
      print e


      # OUTPUT
      <type 'function'>
      <type 'instancemethod '>
      unbound method f() must be called with C instance as first argument (got
      nothing instead)
      f() takes no arguments (1 given)


      When the class C is evaluated the "print type(f)" statement is executed. It
      shows that, at that moment, f's type is 'function'.
      But when you ask, "type(C.f)" it tells you that f is an instance method.
      When you try to call f using "C.f()" you're told that f is an unbound
      method, that must be called with an instance of C as the first argument.
      When you make a method, you usually specify the first argument as being
      "self". In this case "self" would be an instance of C. So, anyway, now f
      appears to expect an argument when it's called. So, we try passing in what
      it appears to expect "C.f(c)", and it tells us that "f() takes no arguments
      (1 given)". Heh.

      I'm not exactly sure what Python's doing behind the scenes but I imagine
      that it's wrapping all function definitions inside the class body: something
      like

      for all functions in the class:
      function = unbound_method( function)

      where unbound_method is a callable that maintains the original function as
      an attribute. When you call the unbound_method, it delegates the call to
      this function f. It's the unbound_method that expects the "instance of C as
      the first argument", but when it passes the argument to its delegate
      function f - well, f doesn't take any arguments, so we get an exception.

      Like I said, I don't know exactly what mechanism are being employed behind
      the scenes, but this is the way I try to understand what's going on.

      Hopefully this is somewhat correct, and helpful,
      Sean


      Comment

      • Bengt Richter

        #4
        Re: Python Cookbook question re 5.6

        On Mon, 15 Dec 2003 08:51:07 -0800, Scott David Daniels <Scott.Daniels@ Acm.Org> wrote:
        [color=blue]
        >Joe wrote:[color=green]
        >> The recipe in question is "Implementi ng 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[/color]
        >
        >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.[/color]
        UIAM that is not quite accurate. The defined "normal functions" you mention
        remain so until dynamically accessed as attributes of the relevant class. If you bypass the
        getattr mechanism (e.g., looking in the class dict), you find that the functions are still "normal":
        [color=blue][color=green][color=darkred]
        >>> class C(object):[/color][/color][/color]
        ... def meth(*args): print 'meth args:', args
        ...[color=blue][color=green][color=darkred]
        >>> c = C()
        >>> C.meth[/color][/color][/color]
        <unbound method C.meth>[color=blue][color=green][color=darkred]
        >>> c.meth[/color][/color][/color]
        <bound method C.meth of <__main__.C object at 0x00902410>>

        but this way you see the plain old function:[color=blue][color=green][color=darkred]
        >>> C.__dict__['meth'][/color][/color][/color]
        <function meth at 0x009050B0>

        if you use getattr, you can see the attribute magic:[color=blue][color=green][color=darkred]
        >>> getattr(C,'meth ')[/color][/color][/color]
        <unbound method C.meth>

        and via an instance:[color=blue][color=green][color=darkred]
        >>> getattr(c,'meth ')[/color][/color][/color]
        <bound method C.meth of <__main__.C object at 0x00902410>>

        calling the plain function:[color=blue][color=green][color=darkred]
        >>> C.__dict__['meth'](1,2,3)[/color][/color][/color]
        meth args: (1, 2, 3)

        trying the same as class attribute, which gets you the unbound method:[color=blue][color=green][color=darkred]
        >>> getattr(C,'meth ')(1,2,3)[/color][/color][/color]
        Traceback (most recent call last):
        File "<stdin>", line 1, in ?
        TypeError: unbound method meth() must be called with C instance as first argument (got int insta
        nce instead)

        you can pass the instance explicitly:[color=blue][color=green][color=darkred]
        >>> getattr(C,'meth ')(c,1,2,3)[/color][/color][/color]
        meth args: (<__main__.C object at 0x00902410>, 1, 2, 3)

        you can make a global binding to the plain function:[color=blue][color=green][color=darkred]
        >>> gm = C.__dict__['meth']
        >>> gm(1,2,3)[/color][/color][/color]
        meth args: (1, 2, 3)

        you can add a method dynamically to the class:[color=blue][color=green][color=darkred]
        >>> C.m2 = lambda *args:args[/color][/color][/color]

        and the getattr magic will do its thing:[color=blue][color=green][color=darkred]
        >>> C.m2[/color][/color][/color]
        <unbound method C.<lambda>>[color=blue][color=green][color=darkred]
        >>> c.m2[/color][/color][/color]
        <bound method C.<lambda> of <__main__.C object at 0x00902410>>[color=blue][color=green][color=darkred]
        >>> c.m2(1,2,3)[/color][/color][/color]
        (<__main__.C object at 0x00902410>, 1, 2, 3)[color=blue][color=green][color=darkred]
        >>> C.m2(1,2,3)[/color][/color][/color]
        Traceback (most recent call last):
        File "<stdin>", line 1, in ?
        TypeError: unbound method <lambda>() must be called with C instance as first argument (got int i
        nstance instead)[color=blue][color=green][color=darkred]
        >>> C.m2(c,1,2,3)[/color][/color][/color]
        (<__main__.C object at 0x00902410>, 1, 2, 3)

        You can also define descriptors that will intercept the getattr magic and alter the behavior,
        if you want to.

        Regards,
        Bengt Richter

        Comment

        • Michele Simionato

          #5
          Re: Python Cookbook question re 5.6

          "Sean Ross" <sross@connectm ail.carleton.ca > wrote in message news:<V_1Db.138 4$Ve.229402@new s20.bellglobal. com>...
          [color=blue]
          > I'm not exactly sure what Python's doing behind the scenes[/color]


          Comment

          Working...