Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - Run all functions in class

I am trying to run all the functions in my class without typing them out individually.

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

I want to do this but with a loop, because my actual class has about 8-10 functions.

x = Foo('hi','bye')
x.bar()
x.foobar()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use dir() or __dict__ to go through all of an object's attributes. You can use isinstance() and types.FunctionType to tell which ones are functions. Just call any that are functions.

Update

As Tadhg commented, inspect.ismethod seems like the best choice. Here's some example code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...