例子
开门见山:
引入
这玩意,看官方还是很难看懂的,不信:
For optional argument actions, the value of dest is normally inferred from the
option strings
. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial – string. If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character. Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name.
不过,我还是决定带你看一看。
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo-bar', '--foo')#1
parser.add_argument('-x', '-y')#2
什么叫做option strings
,上面的#行中,引号里面的,都是。官方还继续区分,'-‘开头的叫做short option string,’–'开头的叫做long option string。
好了,然后再翻译一下官方,即dest你不写,也是有默认值的,例如#1,默认值是foo_bar,#2中默认值是x。
然后在传参时,option strings
都可以传,例如
python test.py -f 1
python test.py --foo 1
但是传递完了之后,属性只能是
parser.foo_bar=1#其他f,foo都报错。
这就是dest。这个时候,你在看例子,发现在例子中foo只是一个幌子,bar才是真正的属性名大佬。