我想对不同的属性使用相同的搜索功能,这取决于用户的选择。在搜索特定动物时,我尝试使用函数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
您可以使用getattr函数执行所需操作:
所以会是:
这是在这样一个假设下的,即动物主义者[i]实际上是一个函数或某种东西,实际上有x方法
相关问题 更多 >
编程相关推荐