假设我们有这样一个类:
class Test(object):
def __init__(self):
pass
def fetch_a(self):
print "a"
def fetch_b(self):
print "b"
我想调用此类的所有函数,以" fetch"开头。在 init 功能中。 我怎么做这项工作
答案 0 :(得分:7)
您可以按照以下方式执行此操作:
class Test(object):
def __init__(self):
for i in dir(self):
if i.startswith('fetch'):
result = getattr(self, i)()
def fetch_a(self):
print "a"
def fetch_b(self):
print "b"
>>> a = Test()
a
b
>>>
如果你只想调用以fetch
开头而不是变量的方法,那么这就可以了:
class Test(object):
def __init__(self):
for i in dir(self):
result = getattr(self, i)
if i.startswith('fetch') and hasattr(result, '__call__'):
result()
答案 1 :(得分:3)
我会这样做:
def __init__(self):
wanted = [m for m in dir(Test) if m.startswith('fetch') and
hasattr(getattr(self, m), '__call__')]
for at in wanted:
end = getattr(self, at)()
答案 2 :(得分:3)
所有答案都假定fetch
的任何方法都是一种方法;但这不能保证。考虑这个例子:
class Foo(object):
fetch_a = 'hello'
def fetch_b(self):
return 'b'
您最终会得到TypeError: 'str' object is not callable
:
>>> a = Foo()
>>> for i in dir(a):
... if i.startswith('fetch'):
... print(getattr(a, i)())
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: 'str' object is not callable
您还需要检查属性是否为方法。由于方法实现__call__
,您可以在检查中使用它:
>>> for i in dir(a):
... if i.startswith('fetch') and hasattr(getattr(a, i), '__call__'):
... print(getattr(a, i)())
...
b
您还可以使用callable()
:
>>> for i in dir(a):
... if i.startswith('fetch') and callable(getattr(a, i)):
... print(getattr(a, i)())
...
b
此方法在Python 2.6中引入,在Python 3.0中删除,然后在Python 3.2中引入。所以要注意你的Python版本。
另一种方法是使用Python 2.1中引入的inspect
module中的isfunction
:
>>> bar = lambda x: x
>>> callable(bar)
True
>>> import inspect
>>> inspect.isfunction(bar)
True
答案 3 :(得分:1)
您可以尝试使用dir:
class Test(object):
def __init__(self):
for name in dir(Test):
if len(name)>4 and name[:5] == "fetch":
eval("self." + name + "()")
def fetch_a(self):
print "a"
def fetch_b(self):
print "b"
z = Test()