Question

I am using argparse in my python program and I want to call a method when I run my software like this :

$ python __init__.py foo

It is easy if I want to call a function instead of a method :

def foo(args):
    pass

def main():
    foo_parser.set_defaults(func=foo)

if __name__ == "__main__":
    main()

How can I replace "func=foo" by "func=MyClass.my_method" ?

Was it helpful?

Solution

You just refer to the method instead of the function. Yup. It's that easy. Instead of

 func = foo

You do

 func = theobject.foo

Done!

OTHER TIPS

You gave the correct answer yourself. Just put:

func = Your_Class.your_method

instead of:

func = foo

Are you looking for something like this :

import argparse

class Myclass(object):

    def foo(self):
        print 'foo'

    def bar(self):
        print 'bar'

class Main(Myclass):

    def __init__(self):
        foo_parser = argparse.ArgumentParser()

        foo_parser.add_argument('method')
        self.args = foo_parser.parse_args()

    def __call__(self, *args, **kws):
        method = self.args.method
        return getattr(self, method)(*args, **kws)

if __name__ == "__main__":
    main = Main()

    main()

example of usage:

$ python test.py foo
'foo'
$ python test.py bar
'bar'

If by "method" you mean "instance method": You can't call an instance method with instance, so you need an instance first. Then, you can just refer to obj.method and get a BoundMethod which remembers the instance (obj) - e.g.:

class Cls:
    def __init__(self, x):
        self.x = x
    def foo(self, new_x):
        self.x = new_x

obj = Cls(1)
foo = obj.foo
foo(2) # same as obj.foo(), but we don't need to keep obj for this!
print(obj.x) #=>2

If it's a static (if so, why? in 99% free functions are simpler to use and work just as well) or class method, just refer to Cls.method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top