在搜索方法python中使用输入参数作为属性

2024-09-29 19:31:02 发布

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

我想对不同的属性使用相同的搜索功能,这取决于用户的选择。在搜索特定动物时,我尝试使用函数search中的输入参数

我可以在打印中使用x,但不能在循环中使用

例如,如果x设置为name,我希望循环使用属性name(animalList[I].name),如果x设置为age,则循环使用age,依此类推。但是当在循环中使用animalList[i].x时,我得到错误“'Animal'对象没有属性'x'”。如何使用设置为x的属性

def search(animalList, x):
    print("What " + x  +" are you searching for? ")
    searchFor = raw_input("Answer: ")
    i = 0
    for djur in animalList:
        if animalList[i].x == searchFor:
            returnVal = "In the park we have: ", animalList[i]
            break
        else:
            i += 1
            returnVal = "No match"
    return returnVal

Tags: 函数用户name功能foragesearch参数
1条回答
网友
1楼 · 发布于 2024-09-29 19:31:02

您可以使用getattr函数执行所需操作:

getattr(animalList[i], x)

所以会是:

def search(animalList, x):
    print("What " + x  +" are you searching for? ")
    searchFor = raw_input("Answer: ")
    for animal in animalList: # this is the proper syntax for for loops
        if getattr(animal, x) == searchFor:
            returnVal = "In the park we have: ", animalList[i]
            break
        else:
            returnVal = "No match"
    return returnVal

这是在这样一个假设下的,即动物主义者[i]实际上是一个函数或某种东西,实际上有x方法

相关问题 更多 >

    热门问题