importing a method

Ben Finney bignose+hates-spam at benfinney.id.au
Sun Nov 27 19:25:15 EST 2005


Flavio <fccoelho at gmail.com> wrote:
> Class soandso:
>     def __init__(self):
>         self.this = 0
>         self.that = 1
>     def meth1(self):
>         ...
>     def meth2(self):
>         ...
>     def custom(self):
>         pass
> 
> I want to allow the user to write a python module that declares a
> function so that myprogram can import it and attribute it to the custom
> method of the soandso object. So far so good, that is an easy thing to
> do in Python.
> 
> import usermodule
> a=soandso()
> a.custom = usermodule.function

Apparently you haven't tested whether this works. It doesn't:

    >>> class Foo(object):
    ...   pass
    ...
    >>> def bar(*args):
    ...   print "bar() got arguments:", args
    ...
    >>> bar("spam", "eggs")
    bar() got arguments: ('spam', 'eggs')
    >>> Foo.bar_method = bar
    >>> Foo.bar_method("spam", "eggs")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: unbound method bar() must be called with Foo instance as first argument (got str instance instead)
  
> But, what if the method had to access the self attributes (self.this
> and self.that) of the soandso object?

To become a method, the function must be bound to an instance, and the
method will then receive the instance as the first argument when
called as a method.

To do this on an already-defined function, use new.instancemethod.

    >>> import new
    >>> help(new.instancemethod)

-- 
 \          "One time a cop pulled me over for running a stop sign. He |
  `\        said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__)             don't believe everything I read.'"  -- Steven Wright |
Ben Finney



More information about the Python-list mailing list