Search code examples
pythonclassmodulegetattr

python how to use getattr on a class


I have a simple use case, I have a class:

class A:
  def meth1(self, name):
    ...
  def meth2(self, name, funcname):
    # funcname is a string 'meth1'
    # how do I invoke meth1 by using funcname string here self.funcname(name)?

I tried using getattr, but was not sure how to go about it.

Thanks!


Solution

  • You could use

    def meth2(self, name, funcname):
        getattr(self, funcname)(name)
    

    since getattr(self, 'meth1') is equivalent to self.meth1.