我希望能够基于用户输入访问类变量,因为我从JiraAPI调用中获得了一个类。比如说
test = my_jira.issue("ISSUE-1799")
test.fields.summary = "Test issue" # sets summary field
# user can enter anything here and I can access any variable from test.fields.
random = "summary"
print(test.fields.(random)) # prints "Test issue"
这可能吗?在test.field
中有一堆类变量,我希望能够根据用户输入的内容访问任何一个类变量。对不起,如果这是错误的。我真的不知道该怎么形容这个
您可以使用
getattr
从类中获取属性。第三个参数是默认参数,如果属性不存在,将返回该参数。考虑到您希望允许用户输入他们想要访问的属性,您一定要使用第三个参数,并准备在属性不存在时向用户传递消息。否则,错误将导致错误破坏脚本如果
test.fields
不是adict
:如果
test.fields
是dict
:您应该注意
random
是一个python模块。使用通用模块名作为变量名不是一种好的做法。如果您碰巧为连接到此脚本的任何内容导入了random
,则可能会出现问题是的,这是可能的,您可以像这样使用内置函数getattr:
相关问题 更多 >
编程相关推荐