문제

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!

도움이 되었습니까?

해결책

You could use

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

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

다른 팁

Could pass the funcname as a parameter to the getattr function and invoke it with the parameter name.

def meth1(self, name):
    print name

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

That would print the value name passed to meth2 via meth1.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top