0

I am trying to call a function from a string in Python as explained in Calling a function of a module from a string with the function's name in Python.

Unfortunately, this doesn't work, and the Python interpreter throws an error: TypeError: 'str' object is not callable

def current(self, t):
    if self.iMode == None:
        return self.i
    else:
        return getattr(self, 'iMode')(t)

The error refers to the last line. iMode has been set to sinx(t), that has been declared in the class.

Can anyone help me please?

4
  • 2
    Can you post the part of the declaration? Commented Jul 24, 2013 at 12:11
  • Maybe you should assign iMode to sinx and not sinx(t). Commented Jul 24, 2013 at 12:12
  • You should use self.iMode is None instead of ==. Commented Jul 24, 2013 at 13:55
  • Questions concerning problems with code you've written must describe the specific problem and include valid code to reproduce it. See SSCCE.org for guidance. Commented Jul 24, 2013 at 14:19

2 Answers 2

2

From the error message it is obvious that your attribute was set to 'sinx(t)' (the string literal).

You should set it the function reference sinx instead, which is a callable.

However, as zhangyangu already said, in you example using getattr() is not needed. Maybe you really want to use a parameter (string reference) instead of the literal 'iMode'?

Sign up to request clarification or add additional context in comments.

Comments

0

From the error, your iMode is a string. The iMode is not a method. There must be something wrong with your declaration. And in the class you can use self.iMode, no need to use getattr.

I think you may look for the function like eval.

Comments

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.