1

I need to call a class method by name, and pass any arguments. Below is an example of what I am try to do:

class C:
    def m(self, s, l=1):
        return "result"
    
    def add(self, op, *args, **kwargs):
        xx = getattr(C, op)(*args, **kwargs)
        print(xx)

ss = C()
ss.add('m', 1, l=5)

This is the error I get:

TypeError: m() missing 1 required positional argument: 's'

How to dynamically pass any argument to any method I call?

zezo
  • 445
  • 4
  • 16

4 Answers4

2

You're missing self. Every instance method that is not called using the syntax instace.method(), shall be called using the syntax class.method(instance):

class C:
    def m(self, s, l=1):
        return "result"
    
    def add(self, op, *args, **kwargs):
        xx = getattr(C, op)(self, *args, **kwargs)
        print(xx)

ss = C()
ss.add('m', 1, l=5)

Another way is to bind the method using getattr(instance, op) instead of geattr(class, op):

class C:
    def m(self, s, l=1):
        return "result"
    
    def add(self, op, *args, **kwargs):
        xx = getattr(self, op)(*args, **kwargs)
        print(xx)

ss = C()
ss.add('m', 1, l=5)

For more info about how this works: Accessing methods via getattr.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
2

You need to use self instead of C.

class C:
    def m(self, s, l=1):
        return "result"
    
    def add(self, op, *args, **kwargs):
        xx = getattr(self, op)(*args, **kwargs)
        print(xx)

ss = C()
ss.add('m', 1, l=5)
Gugu72
  • 2,052
  • 13
  • 35
1

You will have to either

(a) use getattr(self, op)(*args, **kwargs)

That way you are calling the instance method.

-or-

(b) pass self explicitely to the class method of the class C

getattr(C, op)(self, *args, **kwargs)
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
1

Skip s in m() or use self instead of C in getattr.

class C:
    def m(self, l=1):
        return "result"

    def add(self, op, *args, **kwargs):
        xx = getattr(C, op)(*args, **kwargs)
        print(xx)

ss = C()
ss.add('m', 1, l=5)

Or use

class C:
    def m(self,s, l=1):
        return "result"

    def add(self, op, *args, **kwargs):
        xx = getattr(self, op)(*args, **kwargs)
        print(xx)

ss = C()
ss.add('m', 1, l=5)
mhhabib
  • 2,975
  • 1
  • 15
  • 29