functions, classes, bound, unbound?
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Mar 26 20:49:05 EDT 2007
7stud a écrit :
> On Mar 25, 3:09 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
>
>>Here's another way of looking at it::
>>
>> >>> class Test(object):
>> ... pass
>> ...
>> >>> def greet():
>> ... print 'Hello'
>> ...
>>
>>>>Test.greet = greet
>>>>Test.greet
>>
>> <unbound method Test.greet>
>
>
> Interesting. After playing around with that example a bit and finally
> thinking I understood bound v. unbound, I found what appears to be an
> anomaly:
> ------------
> 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>
>
> Why doesn't t.bye cause a method object to be created?
>
(technical answer - I leave to some guru the care to explain the
motivations for this behaviour)
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.
Note that you can override __getattribute__ to change this - but this is
somewhat hackish, and will probably slow down things quite a bit.
FWIW, if you want to dynamically add a method to an instance:
inst.method = func.__get__(inst, inst.__class__)
More information about the Python-list
mailing list