0

I am trying to call fucntions using string value. Here is a simple example of my problem. How to call method(line) properly? I tried different solutions and got success only with @staticmethod but this is not what I want.

class A():

    def prime(self, key):
        line = 'Good'
        method = getattr(A, key)
        method(line)

    def add1(self, string):
        print string + ' day!'

    def add2(self, string):
        print string + ' evening!'



def main():
    test = A()
    test.prime('add1')
    test.prime('add2')

if __name__ == "__main__":
    main()
martineau
  • 119,623
  • 25
  • 170
  • 301
Gatto Nou
  • 89
  • 1
  • 12

2 Answers2

2

You need to pass self to getattr instead of the class name:

method = getattr(self, key)
method(line)

Also, if this is Python 2, you should inherit from object in most cases, to use new-style classes:

class A(object):
Phydeaux
  • 2,795
  • 3
  • 17
  • 35
1

Use operator.methodcaller:

def prime(self, key):
    operator.methodcaller(key, "Good")(self)
chepner
  • 497,756
  • 71
  • 530
  • 681