how to access class methods via their name-as-string

Discussion in 'Python' started by phil_nospam_schmidt@yahoo.com, Jan 31, 2005.

  1. Guest

    I'd like to be able to look up a method name by passing a string with
    the method name. I thought I could use self.__dict__ to get at the
    method names, but as my example shows, this is obviously not working.
    I've also tried self.__class__.__dict__ without success.

    Can anyone point me in the right direction to make this work?

    Thanks,
    Phil

    >>> class a:

    def m1(self):
    print 'm1'
    def __getitem__(self, k):
    return self.__dict__[k]

    >>> class b(a):

    def m2(self):
    print 'm2'


    >>> z=b()
    >>> dir(z)

    ['__doc__', '__getitem__', '__module__', 'm1', 'm2']
    >>> z['m1']

    Traceback (most recent call last):
    File "<pyshell#56>", line 1, in ?
    z['m1']
    File "<pyshell#51>", line 5, in __getitem__
    return self.__dict__[k]
    KeyError: 'm1'
    >>>
     
    , Jan 31, 2005
    #1
    1. Advertising

  2. wrote:
    > I'd like to be able to look up a method name by passing a string with
    > the method name.


    Use getattr:

    py> class A(object):
    .... def f(self):
    .... pass
    .... def g(self):
    .... pass
    ....
    py> class B(A):
    .... def h(self):
    .... pass
    ....
    py> getattr(B(), 'f')
    <bound method B.f of <__main__.B object at 0x011D7790>>
    py> getattr(B(), 'g')
    <bound method B.g of <__main__.B object at 0x01222390>>
    py> getattr(B(), 'h')
    <bound method B.h of <__main__.B object at 0x011D7790>>

    Steve
     
    Steven Bethard, Jan 31, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    7
    Views:
    369
    Lonnie Princehouse
    Oct 25, 2004
  2. Replies:
    4
    Views:
    322
    Cliff Wells
    Oct 26, 2004
  3. Replies:
    1
    Views:
    315
    Alex Martelli
    Oct 26, 2004
  4. spohle
    Replies:
    2
    Views:
    248
    Erik Johnson
    Mar 26, 2007
  5. Kenneth McDonald
    Replies:
    5
    Views:
    355
    Kenneth McDonald
    Sep 26, 2008
Loading...

Share This Page