[英]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. 我尝试使用getattr,但不确定如何去做。
Thanks! 谢谢!
You could use 你可以用
def meth2(self, name, funcname):
getattr(self, funcname)(name)
since getattr(self, 'meth1')
is equivalent to self.meth1
. 因为getattr(self, 'meth1')
等同于self.meth1
。
Could pass the funcname as a parameter to the getattr function and invoke it with the parameter name. 可以将funcname作为参数传递给getattr函数,并使用参数名称进行调用。
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. 这将打印通过meth1传递给meth2的值名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.