RE: apply()?

Discussion in 'Python' started by Ron Griswold, Dec 6, 2005.

  1. Ron Griswold

    Ron Griswold Guest

    Just the ticket. Thank you!

    Ron Griswold
    Character TD
    R!OT Pictures



    -----Original Message-----
    From: python-list-bounces+rgriswold=
    [mailto:python-list-bounces+rgriswold=] On Behalf
    Of Fredrik Lundh
    Sent: Monday, December 05, 2005 3:58 PM
    To:
    Subject: Re: apply()?

    Ron Griswold wrote:

    > I'm almost positive I've seen a function somewhere that will call a
    > method of an object given the method's name. Something like:
    >
    > apply(obj, "func_name", args)
    >
    > is equivalent to:
    >
    > obj.func_name(args)
    >
    > For some reason I thought this was the apply function, but that

    doesn't
    > appear to be the case. Can someone point me in the right direction?


    sounds like you're looking for getattr (get attribute):

    func = getattr(obj, "func_name")
    result = func(args)

    or, in one line:

    result = getattr(obj, "func_name")(args)

    a common pattern is

    try:
    func = getattr(obj, "func_name")
    except AttributeError:
    ... deal with missing method ...
    else:
    result = func(args)

    (this makes sure that an AttributeError raise inside the method isn't
    confused with an AttributeError raise by getattr).

    another pattern is

    func = getattr(obj, "func_name", None)
    if func:
    func(args)

    which only calls the method if it exists. here's a variation:

    func = getattr(obj, "func_name", None)
    if callable(func):
    func(args)

    hope this helps!

    </F>



    --
    http://mail.python.org/mailman/listinfo/python-list
    Ron Griswold, Dec 6, 2005
    #1
    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. chan
    Replies:
    1
    Views:
    3,729
    Nico Debeuckelaere
    Mar 4, 2004
  2. Replies:
    3
    Views:
    386
  3. Markus Meng
    Replies:
    1
    Views:
    1,380
    Mike Treseler
    Jan 15, 2004
  4. Dirk Meusel
    Replies:
    1
    Views:
    2,989
    Dirk Meusel
    Aug 19, 2003
  5. Stefan Siegl
    Replies:
    1
    Views:
    942
    Marrow
    Jul 18, 2003
Loading...

Share This Page