[Python-ideas] Functions and Unbound methods

robert2682 robert2682 at verizon.net
Fri Feb 22 03:28:02 CET 2013


Hi,
> Hi,
>
> I'm new; greetings all!
>
> I'm not sure if this is a bug or feature, but it confused me so I thought
> I'd raise the issue.
>
>
> class a:
>      def b (self):
>        pass
>
>      foo = ('Hello', b)
>
> class c(a):
>      def d(self):
>        t = type (self. __class__. foo [1])
>        print t
>        t = type (self. __class__. b)
>        print t
>
> e = c ()
> e. d()
>
> prints <type 'function'> for the first print,
> and it seems to me it should be an instancemethod
>
> [snip]
> I think what's happening is that it's defining 'b' as a function in the
> class's namespace, storing a reference to that function in the tuple,
> and then, when the class definition ends, it's wrapping the function as
> a method.
>
> You'll find:
>
>   >>> a.foo[1]
> <function b at 0x00B42C30>
>   >>> a.b
> <unbound method a.b>
>   >>> a.b.im_func is a.foo[1]
> True
>

I'm afraid this won't do what I want.  As illustrated below, I want to 
store the
reference from withing the same class, so as to be able to access in 
from a superclass.
(sorry if subclass and superclass is not the correct terminology for Python)

> I'm trying to something like this
>
> class EditPage:
>
>     additonal_buttons = ()
>     def __init__ (self):
>       buts = []
>       for x in addional_butons:
>         if isinstance (x [1], types. UnboundMethodType):     # fails
> because type (x [1]) is function, not UnboundMethod
>           buts. append ((x [0], types. MethodType (x [1], self)))
>         else:
>           buts. append (x)
>
> class TreePage(EditPage):
>     def EditAsText (self):
>        pass
>
>     additional_buttons = (('EditAsText', EditAsText),)
>
>

It might be that Python simple doesn't do exactly what I want.
This is really unusual; mostly I think it's great and highly intuitive.

No biggie; I'm sure I can find a workaround!

Bob



More information about the Python-ideas mailing list