Method binding confusion

Peter Otten __peter__ at web.de
Mon May 3 03:31:40 EDT 2004


A B Carter wrote:

> I'm a bit confused by the behavior of the following code:
> 
> 
> import math
> import myModule
> 
> class Klass(object):
>    def doOperation(self, x, y):
>       return self.operator(x, y)
> 
> class KlassMath(Klass):
>    operator = math.pow
> 
> class KlassMyModule(Klass):
>    operator = myModule.pow
> 
> km = KlassMath()
> kmy = KlassMyModule()
> 
> km.doOperation(2,4)
> km.doOperation(2,4)

Should that be kmy.doOperation(2,4)? Please cut and paste actual code. (The
same goes for the tracebacks)

> The last call fails with "TypeError: takes exactly 2 argumetns (3
> given)" I understand that in KlassMyModule the operator is being
> treated as a method and a reference to the class instance is being
> past as the first argument. And I also understand that Python is
> treating a function from the standard math libary differently from a
> function I defined in my own module. What I don't understand is why.

Assuming that myModule.pow (which you do not to provide) is a function that
takes two arguments, all these will fail:

kmy.doOperation(2, 4)
kmy.operator(2, 4)
km.doOperation(2, 4)
km.operator(2, 4)

If you want to avoid the automatic addition of self, use staticmethod:

>>> def mypow(a, b):
...     return "%s ** %s" % (a, b)
...
>>> class MyClass:
...     operator = staticmethod(mypow)
...
>>> MyClass().operator(2, 4)
'2 ** 4'
>>>

Peter




More information about the Python-list mailing list