Method binding confusion

Peter Otten __peter__ at web.de
Mon May 3 06:12:01 EDT 2004


Eric Brunel wrote:

> I can reproduce the OP's behaviour with old-style classes in Python 2.1.1:

Me too, with new-style classes in Python 2.3.3:

<kmy.py>
import math
#import myModule

def mypow(x, y):
    return "%s ** %s" % (x, y)

class Klass(object):
   def doOperation(self, x, y):
      return self.operator(x, y)

class KlassMath(Klass):
   operator = math.pow

class KlassMyModule(Klass):
   operator = mypow #myModule.pow

km = KlassMath()
kmy = KlassMyModule()

print km.doOperation(2,4)
print kmy.doOperation(2,4)
</kmy.py>

Running the above:
$ python -V
Python 2.3.3
$ python kmy.py
16.0
Traceback (most recent call last):
  File "kmy.py", line 21, in ?
    print kmy.doOperation(2,4)
  File "kmy.py", line 9, in doOperation
    return self.operator(x, y)
TypeError: mypow() takes exactly 2 arguments (3 given)

> I also cannot understand the difference between C1 and C2: math.pow and
> myPow are both functions with two parameters, so why does the first work
> and not the second? Or was it an "unwanted feature" that was removed in a
> later version?
> 
> I also have some difficulty to understand the "automatic addition of self"
> you mention. In what case is it needed? I would have sworn the two classes
> worked...

>>> class A:
...     pass
...
>>> def method(*args):
...     print args
...
>>> A.m = method
>>>
>>> A().m(1,2)
(<__main__.A instance at 0x40296bac>, 1, 2)

See? Although defined outside the class, method() is called with 3
parameters. *I* could have sworn that _that_ would always happen. But:

>>> import math
>>> A.m = math.pow
>>> A().m(1,2)
1.0
>>>

Now I am as confused as you and the OP :-(

Peter





More information about the Python-list mailing list