24

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__()?

4

2 に答える 2

69

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

>>> vars(args)
于 2011-11-01T15:44:50.860 に答える
19
  1. の設計者は、次のarparseように引数にアクセスする方が便利だと感じたようです。

    args.arg_name
    

    それよりも

    args["arg_name"]
    

    ただし、これは好みの問題かもしれません。Namespace特に、。のクラスを除いて、標準ライブラリにクラスがないという事実を考えると、私は辞書を喜んで使用していましたargparse

  2. 辞書を使う。

  3. ここで本当に名前空間が必要な場合は、使用できますinit_function(**args.__dict__)…しかし、お勧めしません。

于 2011-11-01T15:27:04.537 に答える