1

How can I call outside function from inside class function like below?

I know that locals() work when there is no class.

def fn_outside(a):
    print('a:{}'.format(a))
class T:
    def t(self):
        fns = ['fn_outside']
        for fn in fns:
           locals()[fn](1)
t = T()
t.t()

Any help would be appreciated.

6
  • 3
    I think you can call directly? def t(self): fn_outside(1) ? Commented Oct 14, 2021 at 12:39
  • 3
    Why on earth are you doing locals()['fn_outside'](1) ?? Just use fn_outside(1) Commented Oct 14, 2021 at 12:42
  • Why use local(), simply call it fn_outside(1). Then make a object of class T() and call the t(self) method Commented Oct 14, 2021 at 15:24
  • I need to call multiple functions with string names. I edited the body to reflect. Commented Oct 14, 2021 at 22:15
  • If you need to call functions based on strings, you should probably create a dict that maps strings to functions. Commented Oct 14, 2021 at 22:17

1 Answer 1

1

Here is how you would call it, there are supposed to be no Quotation marks around the function, rather you can simply put the function name and then loop through the list, in the end you can put ()

def fn_outside(a):
    print('a:{}'.format(a))
class T:
    def t(self):
        fns = [fn_outside]
        for fn in fns:
           fn(1)
t = T()
t.t()
Sign up to request clarification or add additional context in comments.

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.