使用该getattr()
函数从实例访问任意属性。使用该dir()
函数列出类的所有(继承的)属性。结合这些使得:
foo_attributes = [attr for attr in dir(instance) if attr.startswith('foo')]
for name in foo_attributes:
attr = getattr(instance, name)
if callable(attr):
attr()
我在这里使用了callable()
函数来确保属性确实是一个方法。
快速演示:
>>> class worker:
... def foo(self):
... print "Called foo"
... def foo1(self):
... print "Called foo1"
... def foo2(self):
... print "Called foo2"
...
>>> instance = worker()
>>> foo_attributes = [attr for attr in dir(instance) if attr.startswith('foo')]
>>> for name in foo_attributes:
... attr = getattr(instance, name)
... if callable(attr):
... attr()
...
Called foo
Called foo1
Called foo2