So, in the first case, you should do
if __name__ ... .... args = parser.parse_args() a = A()
A.__init__ can see args because it is global.
I do not understand why you want to make part of the argparse A code; you donβt want it to run every time you use A() , right? You can make only one set of values.
I think it will be a test to make parse_args code a method that can be run as desired after the class is created.
Here is an approach that, I think, has pretty good flexibility:
import argparse class A: def __init__(self, id=None, pw=None, endpoint=None): self.id = id self.pw = pw self.endpoint = endpoint def parse_args(self, argv=None): parser = argparse.ArgumentParser() parser.add_argument('-i', '--id', type=str, help = 'username') parser.add_argument('-p', '--pw', type=str, help ='password') parser.add_argument('-e', '--end_point', type=str , help='end point of api') args = parser.parse_args(argv) self.id = args.id self.pw = args.pw self.endpoint = args.end_point def __str__(self): return 'A(%s,...)'%self.id if __name__ == "__main__": a = A() print(a) a.parse_args() print(a) b = A(id='you') print(b) b.parse_args(['--id','me']) print(b)
Values ββcan be specified when creating an object, from the command line or from custom argv
1610:~/mypy$ python stack39967787.py
===================
My first method (temporarily removed)
class A(): def __init__(self): args = self.parse_args() self.a = args.a etc @static_method def parse_args(self): parser = .... return parser.parse_args()
=======================
Your class A can be used as a Namespace , allowing parse_args directly update attributes (it uses setattr .
import argparse class A: def __init__(self, id=None, pw=None, endpoint=None): self.id = id self.pw = pw self.endpoint = endpoint if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-i', '--id', type=str, help = 'username') parser.add_argument('-p', '--pw', type=str, help ='password') parser.add_argument('-e', '--endpoint', type=str , help='end point of api') args = parser.parse_args() print(args) a = A() parser.parse_args(namespace=a) print(vars(a))
production:
1719:~/mypy$ python stack39967787_1.py --id joe --pw=xxxx -e1 Namespace(endpoint='1', id='joe', pw='xxxx') {'endpoint': '1', 'id': 'joe', 'pw': 'xxxx'}