我可以提供Python类方法作为参数吗? [英] Can I provide Python class method as a parameter?
问题描述
我想提供一个类的方法作为参数。下面是一个简单的例子。
I would like to provide a method of a class as a parameter. Below is a simple example of what I'm after.
说我有一个类定义如下:
Say I have some class defined like this:
class TestClass(object):
def __init__(self):
self.str1 = [1,2,3,4,5]
现在我想向这个类添加一个新方法,该方法将对该列表执行一些操作。此操作将作为此方法的参数提供。所以例如它可能看起来像这样:
Now I want to add a new method to this class that will perform some operation on that list. This operation will be provided as a parameter to this method. So for example it might look something like that:
def testMethod(self, arg1):
print self.str1.arg1(1)
其中 arg1
一个列表类方法。
想法是能够以下面的方式调用该方法:
The idea is being able to call that method in the below manner:
TC = TestClass()
TC.testMethod("index")
$ b b
并且希望获得一个结果,如下所示:
And expecting to get a result as I would get from:
print self.str1.index(1)
如果我运行它,我会得到一个 AttributeError
exception:
If I run it as is, I will get an AttributeError
exception:
AttributeError: 'list' object has no attribute 'arg1'
注意:此问题被要求归纳另一个问题,我描述了此处。
NOTE: This question was asked to generalize another issue, I described here.
推荐答案
print getattr(self.str1, arg1)(1)
这篇关于我可以提供Python类方法作为参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!