Re: apply()?

Discussion in 'Python' started by Fredrik Lundh, Dec 5, 2005.

  1. 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>
     
    Fredrik Lundh, Dec 5, 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,802
    Nico Debeuckelaere
    Mar 4, 2004
  2. Replies:
    3
    Views:
    407
  3. Markus Meng
    Replies:
    1
    Views:
    1,453
    Mike Treseler
    Jan 15, 2004
  4. Dirk Meusel
    Replies:
    1
    Views:
    3,071
    Dirk Meusel
    Aug 19, 2003
  5. Stefan Siegl
    Replies:
    1
    Views:
    994
    Marrow
    Jul 18, 2003
Loading...

Share This Page