Obtaining an member function by name

Bengt Richter bokr at oz.net
Sat Nov 19 16:48:36 CET 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()?
>Surely somebody knows..
Sorry, clean forgot about the strings.

 >>> class foo:
 ...     def bar(self): return self, 'bar is the name'
 >>> # The definition is at global scope, so 'foo' will show up
 ... # in the globals() directory, which we can access with appended ['foo']
 >>> globals()['foo']
 <class __main__.foo at 0x02EE9C2C>
 >>> #if you want the 'bar' attribute using the string
 ... getattr(globals()['foo'], 'bar')
 <unbound method foo.bar>
 >>> foo.bar
 <unbound method foo.bar>

Note that getting an attribute does some "binding" magic if the
attribute has certain qualitites. In this case the bar function
is associated with the foo class to become an "unbound method"

Nit: usual convention is to spell class names with leading upper case.
Then you can e.g. use the lower case same name for an instance of the
class without confusions. Nit2: using new-style classes, which derive
from object (or also other bases, but at least object or type) is now
recommended, so you get the full-fledged attribute machinery that supports
much of the latest magic. So write the above more like

    class Foo(object):
        def bar(self): return self, 'bar is the name'

Bengt Richter

More information about the Python-list mailing list