Obtaining an member function by name

Bengt Richter bokr at oz.net
Sat Nov 19 10:30:51 EST 2005


On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <guy.lateurNNOOSSPPAAMM at pandora.be> wrote:

>Hi all,
>
>Suppose you have this class:
>
>class foo:
>    def bar():
>
>Suppose you also have the strings "foo" and "bar". How can you obtain the 
>function foo.bar()?
Why don't you type these things into an interactive python session
and see what happens? Also, foo.bar will be an unbound method of foo,
not a function per se. You could experiment a little, e.g.,

 >>> class foo:
 ...     def bar():
 ...
   File "<stdin>", line 3

     ^
 IndentationError: expected an indented block
 >>> class foo:
 ...     def bar(): return 'bar is the name' # you could have done this
 ...
 >>> foo.bar()
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: unbound method bar() must be called with foo instance as first argument (got nothing
 instead)
 >>> foo()
<__main__.foo instance at 0x02EF3D8C>
 >>> foo.bar(foo())
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: bar() takes no arguments (1 given)
 >>> class foo:
 ...     def bar(self): return self, 'bar is the name' # you could have done this
 ...
 >>> fooinst = foo()
 >>> fooinst
 <__main__.foo instance at 0x02EF756C>
 >>> foo.bar(fooinst)
 (<__main__.foo instance at 0x02EF756C>, 'bar is the name')
 >>> fooinst.bar
 <bound method foo.bar of <__main__.foo instance at 0x02EF756C>>
 >>> fooinst.bar()
 (<__main__.foo instance at 0x02EF756C>, 'bar is the name')
 >>> foo.bar.im_func
 <function bar at 0x02EF5764>
 >>> foo.bar.im_func('first arg')
 ('first arg', 'bar is the name')
 >>> fooinst.bar
 <bound method foo.bar of <__main__.foo instance at 0x02EF756C>>
 >>> fooinst.bar.im_func
 <function bar at 0x02EF5764>
 >>> fooinst.bar.im_func(1234)
 (1234, 'bar is the name')
 >>> fooinst.bar()
 (<__main__.foo instance at 0x02EF756C>, 'bar is the name')
 >>> foo.bar(333)
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: unbound method bar() must be called with foo instance as first argument (got int inst
 ance instead)
 >>> foo.bar(fooinst)
 (<__main__.foo instance at 0x02EF756C>, 'bar is the name')

Someone can explain. If you do some of your own work, it will help even the load.
Have you looked at any documentation? Start at http://www.python.org/
and click a few things. There seems to be a beginners guide link under documentation
in the sidebar to the left ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list