functions, classes, bound, unbound?

irstas at gmail.com irstas at gmail.com
Mon Mar 26 18:50:20 CEST 2007


On Mar 26, 7:15 pm, "7stud" <bbxx789_0... at yahoo.com> wrote:
> 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?

Because that would be bad and unexpected behaviour. I might want to
store callback functions to an object as attributes. It wouldn't make
sense for the functions to be bound to the container object when I'd
access them.

Of course, "Test.func = greet; print Test.func" is also "unexpected
behaviour" as Test.func is not same as Test.__dict__['func']. But it's
unexpected in a good way, because it facilitates the way classes are
usually used. The whole point of the magic is to make common idioms
simple.




More information about the Python-list mailing list