Home > database >  How do I elegantly call a bunch of methods on one object?
How do I elegantly call a bunch of methods on one object?

Time:07-15

I apologize if this seems like an obvious question, but I cannot find the word to search for to describe this.

I am currently writing this:

foo.cat()
foo.dog()
foo.fish()
foo.moose()
foo.horse()
...

I'd rather write this:

many foo:
    dog()
    cat()
    fish()
    horse()
    ...

How can I do this in Python 3? Is there a keyword, or something?

CodePudding user response:

  1. You could use dog() - only one function with that specific name
  2. you could make new function that will call all of them
  3. use something like this
exec_methods = ["dog", "cat", "fish"]
for method in exec_methods:
    getattr(x, method)()

CodePudding user response:

If you want to shorten "foo", you can do

for f in [foo]:
    f.dog()
    f.cat()
    f.fish()
    f.horse()

CodePudding user response:

You could define a methodscaller function that was somewhat of hybrid between what operator.itemgetter() and operator.methodcaller() do that created something callable that would call all the methods specified when it was called. The function itself would be generic in the sense that it can be used with any type of object and/or series of methods.

The following demonstrates what I mean:

class Foo:
    def dog(self): print('dog called')
    def cat(self): print('cat called')
    def fish(self): print('fish called')
    def moose(self): print('moose called')
    def horse(self): print('horse called')


def methodscaller(*methods):
    """Return callable object that calls the methods named in its operand."""
    if len(methods) == 1:
        def g(obj):
            return getattr(obj, methods[0])
    else:
        def g(obj):
            return tuple(getattr(obj, method)() for method in methods)
    return g


call_methods = methodscaller('dog', 'cat', 'fish', 'moose', 'horse')
call_methods(Foo())
  • Related