functions, classes, bound, unbound?

7stud bbxx789_05ss at yahoo.com
Tue Mar 27 04:49:24 CEST 2007


On Mar 26, 6:49 pm, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> ------------
> class Test(object):
>         pass

> def greet(x):
>         print "hello"

> Test.func = greet
> print Test.func

> t = Test()
> print t.func

> def sayBye(x):
>         print "bye"

> t.bye = sayBye
> print t.bye
> ------------output:
> <unbound method Test.greet>
> <bound method Test.greet of <__main__.Test object at 0x6dc50>>
> <function sayBye at 0x624b0>
>
>
> Because t.bye is an attribute of instance t, not of class Test.  A
> descriptor object has to be a class attribute for the descriptor
> protocol to be invoked.

Hurray!  Like this:


t.func -> __getattribute__() -> __get__() -> create method object and
return it
t.bye  -> __getattribute__() -> return sayBye


> FWIW, if you want to dynamically add a method to an instance:
>    inst.method = func.__get__(inst, inst.__class__)

Nice.





More information about the Python-list mailing list