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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • phil_nospam_schmidt@yahoo.com

    #1

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

    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
    [color=blue][color=green][color=darkred]
    >>> class a:[/color][/color][/color]
    def m1(self):
    print 'm1'
    def __getitem__(sel f, k):
    return self.__dict__[k]
    [color=blue][color=green][color=darkred]
    >>> class b(a):[/color][/color][/color]
    def m2(self):
    print 'm2'

    [color=blue][color=green][color=darkred]
    >>> z=b()
    >>> dir(z)[/color][/color][/color]
    ['__doc__', '__getitem__', '__module__', 'm1', 'm2'][color=blue][color=green][color=darkred]
    >>> z['m1'][/color][/color][/color]
    Traceback (most recent call last):
    File "<pyshell#5 6>", line 1, in ?
    z['m1']
    File "<pyshell#5 1>", line 5, in __getitem__
    return self.__dict__[k]
    KeyError: 'm1'[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

  • Steven Bethard

    #2
    Re: how to access class methods via their name-as-string

    phil_nospam_sch midt@yahoo.com wrote:[color=blue]
    > I'd like to be able to look up a method name by passing a string with
    > the method name.[/color]

    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

    Comment

    Working...