基于用户输入访问类变量



我希望能够根据用户输入访问类变量,因为我从 JIRA API 调用中获取了一个类。例如

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:

print(getattr(test.fields, random))

您可以使用getattr从类中获取属性。第三个参数是默认参数,如果属性不存在,将返回该参数。考虑到您希望允许用户键入他们想要访问的属性,您绝对应该使用第三个参数,并准备好在该属性不存在时向用户传递消息。否则,错误将导致错误破坏脚本。

如果test.fields不是dict

#example
attrName = input("Type the attribute name you would like to access: ")
attr = getattr(test.fields, attrName, None)
if attr is None:
print(f'Attribute {attrName} does not exist')
else:
print(f'{attrName} = {attr}')

如果test.fieldsdict

attrList = [*test.fields]  #list of keys
attrName = input("Type the attribute name you would like to access: ")
if attrName in attrList:
attr = test.fields[attrName]
print(f'{attrName} = {attr}')
else:
print(f'Attribute {attrName} does not exist')

你应该注意,random是一个python模块。使用常用模块名称作为变量名称不是好的做法。如果您碰巧为与此脚本相关的任何内容导入random,则可能会遇到问题。

最新更新