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
  • 112,593
  • 23
  • 157
  • 280
Gatto Nou
  • 101
  • 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
  • 15
  • 35
1

Use operator.methodcaller:

def prime(self, key):
    operator.methodcaller(key, "Good")(self)
chepner
  • 446,329
  • 63
  • 468
  • 610