Namespace, argparse, and usage

匆匆过客 提交于 2019-12-05 09:20:23

问题


This is really a few questions:

  1. Is there a reason argparse uses a namespace instead of a dictionary?

  2. Assuming I have a class with __init__(self, init_method, *args). The init_method parameter tells the init_function which way I want to initialize the class, while arg parameter gives all the arguments neccesary for the init. The arguments may be different for different methods. Should I use a dictionary, or a namespace?

  3. Assuming that I use a namespace, how do I pass the namespace to __init__()?


回答1:


  1. The designers of arparse apparently felt it would be more convenient to access arguments as

    args.arg_name
    

    rather than

    args["arg_name"]
    

    This might be a matter of taste, though. I would have happily gone with the dictionary, especially given the fact that there is no Namespace class in the standard library, except for the one in argparse.

  2. Use a dictionary.

  3. If you really want a namespace here, you can use init_function(**args.__dict__)…but I don't recommend it.




回答2:


It is easy to convert a Namespace into a dictionary using vars():

>>> vars(args)


来源:https://stackoverflow.com/questions/7968697/namespace-argparse-and-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!