根据用户输入访问 class 变量

Accessing class variable based on user input

我希望能够根据用户输入访问 class 变量,因为我收到来自 JIRA API 的 class 调用。例如

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 中有一堆 class 变量,我希望能够根据用户输入的内容访问任何一个。对不起,如果这是不正确的。我真的不知道怎么形容这个。

可以,您可以像这样使用内置函数 getattr

print(getattr(test.fields, random))

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

如果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,您可能会遇到问题。