functions, classes, bound, unbound?

7stud bbxx789_05ss at yahoo.com
Mon Mar 26 12:15:04 EDT 2007


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?


> ... under the covers, classes are actually using
> doing something like this::
>
>      >>> Test.__dict__['greet'].__get__(None, Test)
>      <unbound method Test.greet>
>      >>> Test.greet == Test.__dict__['greet'].__get__(None, Test)
>      True
>

...via __getattribute_, right?

> ... if you want to get a method from a function, you can always do that
> manually yourself::
>
>      >>> greet.__get__(None, Test)
>      <unbound method Test.greet>

Manually creating a method object.  Nice.




More information about the Python-list mailing list