Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串/参数操作_Python_String_Syntax_Syntax Error_User Input - Fatal编程技术网

Python字符串/参数操作

Python字符串/参数操作,python,string,syntax,syntax-error,user-input,Python,String,Syntax,Syntax Error,User Input,我有一个函数,它有一个name1值,该值是通过用户输入通过sys.argv.pop()获得的,该值指示要使用myconfig.py中的哪个参数。作为一个对python比较陌生的人,我想知道这样做的正确方法是什么,这样我就可以正确地访问所需的数据 完成后,我希望参数的作用如下:myconfig.Oink['lower\u bound']或myconfig.Woof['lower\u bound'] > self.do_x(id, myconfig."name1".format(name1)[

我有一个函数,它有一个
name1
值,该值是通过用户输入通过
sys.argv.pop()
获得的,该值指示要使用
myconfig.py
中的哪个参数。作为一个对python比较陌生的人,我想知道这样做的正确方法是什么,这样我就可以正确地访问所需的数据

完成后,我希望参数的作用如下:
myconfig.Oink['lower\u bound']
myconfig.Woof['lower\u bound']

> self.do_x(id, myconfig."name1".format(name1)['lower_bound'],
> myconfig."name1".format(name1)['upper_bound'])
>                                                  ^ SyntaxError: invalid syntax
__________________________________________________________________

> myconfig.py
> 
> Oink = dict(lower_bound = 874,upper_bound = 1983,) 

> Woof = dict(lower_bound = 1,upper_bound = 984,)

您可以通过以下方式实现此目的:

请注意,
getattr
区分大小写,这意味着
getattr(myconfig,'Oink')
将产生正确的值,
getattr(myconfig,'Oink')
将产生
AttributeError


如果要处理无效值,可以使用:


如果希望使用默认值而不是引发
ValueError
,则可以使用
default
关键字参数作为
getattr

default = dict(lower_bound=20, upper_bound=50)
values = getattr(myconfig, name1, default=default)
self.do_x(values['lower_bound'], values['upper_bound'])

理想情况下,您应该将
myconfig
更改为dict而不是对象,因为dict用于按名称查找值:
myconfig[name1][“下限”]
。如果由于某种原因不能这样做,可以使用函数,比如
getattr(myconfig,name1)[“下限”]
。但是,正如您所看到的,当您需要
getattr
时,这是一个很好的迹象,表明您可能想要一个dict。
if not hasattr(myconfig, name1):
    raise ValueError('Invalid value {}'.format(name1))

values = getattr(myconfig, name1)
self.do_x(values['lower_bound'], values['upper_bound'])
default = dict(lower_bound=20, upper_bound=50)
values = getattr(myconfig, name1, default=default)
self.do_x(values['lower_bound'], values['upper_bound'])