简体   繁体   中英

metaprograming on python Namespace object

I want to assign all the items into Namesapce object dynamically

But it seems not work, how could I get it.

export_file={
    "default_value": "{0}_default_value.txt".format(args.cam_ip),
    "msword": "{0}_msword.txt".format(args.cam_ip),
}

args = argparse.Namespace()

for key,value in export_file.iteritems():
    args.key = value

Use setattr :

for key, value in export_file.iteritems():
    setattr(args, key, value)

Example usage of setattr :

>>> class Namespace:
...     def __init__(self):
...         self.a = 1
...
>>> ns = Namespace()
>>> ns.a
1
>>> setattr(ns, 'a', 9)
>>> ns.a
9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM