运行类中的所有函数

新手上路,请多包涵

我试图运行我班上的所有功能,而不是单独输入它们。

 class Foo(object):
    def __init__(self,a,b):
        self.a = a
        self.b=b

    def bar(self):
        print self.a

    def foobar(self):
        print self.b

我想这样做但是有一个循环,因为我的实际类有大约 8-10 个函数。

 x = Foo('hi','bye')
x.bar()
x.foobar()

原文由 collarblind 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 596
1 个回答

您可以使用 dir()__dict__ 遍历对象的所有属性。您可以使用 isinstance()types.FunctionType 来判断哪些是函数。只需调用任何函数即可。

更新

正如 Tadhg 评论的那样, inspect.ismethod 似乎是最佳选择。下面是一些示例代码:

 import inspect
from itertools import ifilter

class Foo(object):
    def foo1(self):
        print('foo1')

    def foo2(self):
        print('foo2')

    def foo3(self, required_arg):
        print('foo3({!r})'.format(required_arg))

f = Foo()
attrs = (getattr(f, name) for name in dir(f))
methods = ifilter(inspect.ismethod, attrs)
for method in methods:
    try:
        method()
    except TypeError:
        # Can't handle methods with required arguments.
        pass

原文由 Don Kirkby 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏