Method binding confusion
Robert Brewer
fumanchu at amor.org
Mon May 3 12:06:46 EDT 2004
Peter Otten wrote:
> <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>
>
> >>> 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 :-(
Specifically, one needs to explain why:
>>> kmy.KlassMath.operator
<built-in function pow>
>>> kmy.KlassMath().operator
<built-in function pow>
but:
>>> kmy.KlassMyModule.operator
<unbound method KlassMyModule.mypow>
>>> kmy.KlassMyModule().operator
<bound method KlassMyModule.mypow of <kmy.KlassMyModule object at
0x0114DCD0>>
...which I haven't got the vocabulary or time for right now. ;(
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list