Home > Net >  How can I either use arguments or constructor values in a python class
How can I either use arguments or constructor values in a python class

Time:01-16

I have a python class and a main function next to it so I can execute it from command line. My init function deals my provided arguments:

import argparse

class Tester:

    def __init__(self):
        self.args_parser = argparse.ArgumentParser(description='Test')
        self.args = self.__parse_parameters()
...


if __name__ == "__main__":
    tester = Tester()

This way, when I execute the above file from command line, for example:

#python teser.py --test eating --lowcarb

I can provide the parameters and they will eventually get passed to __parse_parameters function. All good.

My question is, how can I pass these parameters to the class if I decide to use this class from python code?

CodePudding user response:

Do you mean this?

import argparse

class Tester:

    def __init__(self, answer, foo):
        print(answer)
        self.args_parser = argparse.ArgumentParser(description='Test')
        self.args = self.__parse_parameters()

if __name__ == "__main__":
    tester = Tester(answer=42, foo='bar')

Another option (depending on what you mean) is to move the ArgumentParser outside the class:

import argparse

class Tester:

    def __init__(self, args):
        self.args = args

if __name__ == "__main__":
    args_parser = argparse.ArgumentParser(description='Test')
    tester = Tester(args_parser.parse_args())

This way you can pass any args:

tester2 = Tester(('arg0', 'arg1'))

CodePudding user response:

Look at this example from the official tutorial:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print(f"the square of {args.square} equals {answer}")
elif args.verbosity == 1:
    print(f"{args.square}^2 == {answer}")
else:
    print(answer)

You can use add_argument to specifically indicate an argument, and then pass it to the class using args.<argument-name>.

Personally I would parse the arguments in a function in main, and pass the parameters to the class, so it will look something like:

if __name__ == '__main__':
    args = parse_args()
    tester = Tester(args.arg1, args.arg2, ...)
  • Related