[Tutor] bound vs. unbound method?

Kalle Svensson kalle@gnupung.net
Wed, 21 Nov 2001 17:02:50 +0100


[Pijus Virketis]
> Hi!
> 
> I found a brief mention of bound and unbound methods in Python on
> comp.lang.python archives. What is the difference between the two?
[snip]

Consider a function and a method:

def f(x):
    print x

class C:
    def m(self, x):
        print x

The function takes one argument and prints it, so does the method, if used on
an instance:

>>> c = C()
>>> f(1)
1
>>> c.m(1)
1

This means the first method argument, self, appeared from nowhere.  This is
because the method is bound to the instance c.  When a method is not bound to
any instance, you have to supply all arguments yourself, like:

>>> C.m(c, 1)
1

This also means that c.m and C.m are not the same thing.  They're *almost* the
same, but c.m is bound to the instance c, and C.m is unbound.

Does this help?

Peace,
  Kalle
-- 
[   International: http://www.gnupung.net/   ]
[ Svenska: http://www.lysator.liu.se/~kalle/ ]