基于用户输入访问类变量

2024-10-01 11:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 用户testfieldfieldsmysetsjirarandom
2条回答

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

如果test.fields不是adict

#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,则可能会出现问题

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

print(getattr(test.fields, random))

相关问题 更多 >