Confused with methods

jfj jfj at freemail.gr
Mon Feb 7 19:23:29 EST 2005


Hello Diez.
I sent a reply to the previous message requesting an example of
what would break, but unfortunatelly it didn't make it in python-list.
Here it is for the record [
> Diez B. Roggisch wrote:
> 
>>If things worked as you wanted it to, that would mean that passing bound
>>method as argument to a class and storing it there to an instance variable
>>that would "eat up" the arguments - surely not the desired behaviour.
> 
> 
> Could you please give an example of this ?
> 
> If you mean:
> 
>    class A:
>       def f(x):
>          print x
> 
>    class B:
>       pass
> 
>    a=A()
>    B.f = a.f
>    b=B()
>    b.f()     #surprise: it works!!
> 
> then that is equally "weird" as my case. "eat up" sounds
> rather bad but all what will happen is an argument number
> mismatch.
> In fact is seems more appropriate to use a.f.im_func in this
> case to "convert the bound method to an unbound one".
> 
> Maybe this happens more often?
> 
> 
> Thanks,
> 
> G.
> 
]

Diez B. Roggisch wrote:

>>If there a good reason that the __get__ of a boundmethod does not
>>create a new boundmethod wrapper over the first boundmethod?
> 
> 
> I already gave you the good reason:
> 
> class A:
>    def callback(self, arg):
>        print self, arg
> 
> def callback(arg):
>     print arg
> 
> class DoSomethingWithCallback:
>     def __init__(self, cb):
>         self.cb = cb
> 
>     def run(self):
>         for i in xrange(100):
>              self.cb(i)
> 
> u = DoSomethingWithCallback(A().callback)
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Oops!!!
I think it would be more obvious to somebody who doesn't know
the python internals, to say:
  # take the callback from A and install it to DSWC
  u=DoSomethingWithCallback( A.callback)
or
  u=DoSomethingWithCallback (A().callback.im_func)
or
  u=DoSomethingWithCallback (A().im_class.callback)


> v = DoSomethingWithCallback(callback)
> 
> # would crash if your suggestion worked
> u.run()
> v.run()
> 

It would complain about not enough arguments.
As it does in the case I'm confused about!

> If you are after currying - look at the cookbook, there are recipes for
> that.

I'm satistfied with Alex's response that it is like that for backwards
compatibility, but in Python 3000 it may be the other way around.


Thanks all.

jfj




More information about the Python-list mailing list