0
class A:

   def f1(a,b):
       return a+b

   def f2(a,b):
       return a*b

   def f3(a,b):
       return a-b

obj = A()
string = 'f1'

I need to access method f1 using the string. Something like :

obj.string(a,b)

How can I achieve this ??
getattr(obj, ' f1 ') does not send any parameters a,b to the funct.
Converting string into an object, is not helping. I even tried function mapping, but that too caused errors.

Addi
  • 1
  • 1
  • 1
    [`getattr`](https://docs.python.org/3/library/functions.html?highlight=getattr#getattr) does that. i.e. `getattr(obj, "f1")`. – hiro protagonist Mar 11 '20 at 12:10
  • 1
    Why do you have a method name in a string in the first place? – chepner Mar 11 '20 at 12:11
  • Does this answer your question? [How to access object attribute given string corresponding to name of that attribute](https://stackoverflow.com/questions/2612610/how-to-access-object-attribute-given-string-corresponding-to-name-of-that-attrib) – con ko Mar 11 '20 at 12:13
  • How to send the parameters a,b along ?? – Addi Mar 11 '20 at 12:23
  • @Addi `getattr(obj, "f1")(a, b)` except... your methods should be static-/class-methods. – hiro protagonist Mar 11 '20 at 12:28

0 Answers0