Skip to content Skip to sidebar Skip to footer

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 b

Solution 1:

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


classFoo(object):
    deffoo1(self):
        print('foo1')

    deffoo2(self):
        print('foo2')

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

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

Solution 2:

This is the easiest way to solve this problem, also it's kind of flexible to do changes in it.

import threading
from threading import Thread

classClassName():
    deffunc1(self):
        print ('2')

    deffunc2(self):
        print ('3')

    defrunall(self):
        if __name__ == '__main__':
            Thread(target = self.func1).start()
            Thread(target = self.func2).start()
run = ClassName()
run.runall() # will run all the def's in the same time

Solution 3:

You can get list of all 'public' methods of your instance:

x = Foo('hi','bye')

public_method_names = [methodformethodin dir(x) if callable(getattr(x, method)) if not method.startswith('_')]  # 'private' methods startfrom _
formethodin public_method_names:
    getattr(x, method)()  # call

See more about getattr Actually, Python doesn't have public or private semantic, you can read that if interested

Solution 4:

While I realize it's not what you're asking, I think what you're asking (execute all methods) in general is a bad idea, because the object's API is not internal to the object. (E.g. the user has to write functionality (namely exactly the functionality that you're asking for) in order to use the class.)

You're much better off defining a list of methods that you want to run yourself. E.g.:

exec_methods = ["bar", "foobar"]
formethodin exec_methods:
    getattr(x, method)()

Solution 5:

While I do not particularly recommend calling all the methods on an object since as soon as you add some that require an argument it will obviously fail, you could use a decorator to label the methods that represent a test case and then search for all the ones that have said label:

deftester_method(f):
    f._is_for_test = True#add an arbitrary attribute to the function, completely supported for exactly this reason.return f

defcall_all_tester_methods(x):
    """finds all attributes with a ._is_for_test attribute of their 
own and calls all of them in no guaranteed order"""
    methods = {}
    for name indir(x):
        attr = getattr(x,name)
        ifgetattr(attr,"_is_for_test",False):
            methods[name] = attr
    for name,method in methods.items():
        #print("calling: {}".format(name))
        method()

classFoo(object):
    def__init__(self,a,b):
        self.a = a
        self.b=b

    @tester_methoddefbar(self):
        print(self.a)

    @tester_methoddeffoobar(self):
        print(self.b)

    defothermethod_not_for_test(self,arg):
        return self.a + arg #this is not included in the test case

obj = Foo('hi','bye')
call_all_tester_methods(obj)

Post a Comment for "Run All Functions In Class"