10

How can you execute a method by giving its name, from another method that is in the same class with the called method? Like this:

class Class1:
    def __init__(self):
        pass
    def func1(self, arg1):
        # some code
    def func2(self):
        function = getattr(sys.modules[__name__], "func1") # apparently this does not work

Any suggestion?

2 Answers 2

11

how about getattr(self, "func1")? Also, avoid using the name function

For example:

>>> class C:
...  def f1(self, arg1): print arg1
...  def f2(self): return getattr(self, "f1")
... 
>>> x=C()
>>> x.f2()(1)
1
Sign up to request clarification or add additional context in comments.

1 Comment

There is no reason to use getattr if you know the method you want -- just grab it.
6

You should get the attribute from the class, not the module.

def func2(self):
    method = getattr(self, "func1")
    method("arg")

But you should also check that it's callable.

if callable(method):
    method("arg")

This will avoid calling something that you didn't expect to get. You may want to raise your own exception here if it is not callable.

4 Comments

getattr is unnecessary when you know the name of the method. Also, why check if it's callable? Either it is (and should be if it's a method), or it will raise an exception -- which is the proper way to deal with an error.
@Ethan presumably the name would actually be a variable, and this is just an example. The callable check avoids errors, in one line of code, and the intent is clearer, since getattr can return any kind of attribute and not just methods.
Hmm... okay, I can see the name being in a variable (the original question is not well worded), although I still mostly disagree with the callable check: if it's not callable, what do you do? raise an exception? Unless you have good reason, just let the exception from trying to call a non-callable object perculate up.
@Ethan those are good questions, but out of the scope of the OP question. The OP will have to decide those things taking other design criteria into consideration. But in general I think error checking, or avoiding errors, is a good thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.