在搜索方法python中使用输入参数作为属性
我想对不同的属性使用相同的搜索功能,这取决于用户的选择。搜索特定动物时,我尝试使用函数搜索中的输入参数 我可以在打印中使用x,但不能在循环中使用 例如,如果x设置为name,我希望循环使用属性name(animalList[I].name),如果x设置为age,则循环使用属性name,依此类推。但是在循环中使用animalList[i].x时,我得到错误“'Animal'对象没有属性“x””。如何使用设置为x的属性在搜索方法python中使用输入参数作为属性,python,attributes,Python,Attributes,我想对不同的属性使用相同的搜索功能,这取决于用户的选择。搜索特定动物时,我尝试使用函数搜索中的输入参数 我可以在打印中使用x,但不能在循环中使用 例如,如果x设置为name,我希望循环使用属性name(animalList[I].name),如果x设置为age,则循环使用属性name,依此类推。但是在循环中使用animalList[i].x时,我得到错误“'Animal'对象没有属性“x””。如何使用设置为x的属性 def search(animalList, x): print("Wh
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
您可以使用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
这是在假设animalList[i]实际上是一个函数或某个具有x方法的东西的情况下