我从这个类创建了任意数量的对象:
class Person:
def __init__(self, name, email):
self.name = name
self.email = email
我有这些对象的列表:
myList = []
JohnDoe = Person("John Doe", "jdoe@email.com")
BobbyMcfry = Person("Bobby Mcfry", "bmcfry@email.com")
WardWilkens = Person("Ward Wilkens", "wwilkens@email.com")
myList.append(JohnDoe)
myList.append(BobbyMcfry)
myList.append(WardWilkens)
我想检查某人是否存在,如果存在,则返回他们的属性 - 如果不存在,请说:
x = input("Who to check for? ")
for i in myList:
if i.name == x:
print("Name: {0}\nEmail: {1}".format(i.name, i.email))
else:
print("{0} is not on the manifest.".format(x))
这种方法有效,但为 myList 中的每个人返回一个或另一个 - 我只想要一个返回...
我意识到我需要做一些事情
if val in myList:....
但是我很难在不遍历每个对象的情况下如何说出“val”应该是什么