简体   繁体   中英

Calling functions / class methods inside a for loop

I'm working on a some classes, and for the testing process it would be very useful to be able to run the class methods in a for loop. I'm adding methods and changing their names, and I want this to automatically change in the file where I run the class for testing.

I use the function below to get a list of the methods I need to run automatically (there are some other conditional statements I deleted for the example to make sure that I only run certain methods that require testing and which only have self as an argument)

def get_class_methods(class_to_get_methods_from):
    import inspect
    methods = []
    for name, type in (inspect.getmembers(class_to_get_methods_from)):
        if 'method' in str(type) and str(name).startswith('_') == False:
            methods.append(name)
    return methods

Is it possible to use the returned list 'methods' to run the class methods in a for loop?

Or is there any other way to make sure i can run my class methods in my testingrunning file without having to alter or add things i changed in the class?

Thanks!

Looks like you want getattr(object, name[, default]) :

class Foo(object):
    def bar(self):
        print("bar({})".format(self))


f = Foo()
method = getattr(f, "bar")
method()

As a side note : I'm not sure that dynamically generating lists of methods to test is such a good idea (looks rather like an antipattern to me) - now it's hard to tell without the whole project's context so take this remarks with the required grain of salt ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM