我的代码中的“get_info”部分遇到了一些问题。具体来说,只要我输入自身部分,我的get_info就会工作,它对应于类中的实例,即
x=Person('Joe', 'Schmoe', '123-456-7890')
x.get_info()
但是,我不确定如何通过搜索姓氏来显示联系人的信息。据我所知,类不可迭代,所以我不能使用for循环。很明显,我的代码的底部有一些问题,从“elif x == 2:”开始,这是我的代码:
class Person:
def __init__(self, first_name, last_name, phone_number):
self.first_name=first_name
self.last_name=last_name
self.phone_number=phone_number
print("Initialized Person: ", self.first_name)
def get_info(self):
print(self.first_name, self.last_name, self.phone_number)
class Friend(Person):
def __init__(self, first_name, last_name, phone_number, email, birth_date):
Person.__init__(self, first_name, last_name, phone_number)
self.email = email
self.birth_date = birth_date
print("Initialized Friend:", self.first_name)
def get_info(self):
print(self.first_name, self.last_name, self.phone_number, self.email, self.birth_date)
def main():
exitprogram=False
a=("1. Add Contact")
b=("2. Lookup Contact")
c=("3. Exit Program")
while exitprogram==False:
print(a)
print(b)
print(c)
x=(int(input("Please select a number: ")))
if x==1:
a1=("1. Add Regular Person")
a2=("2. Add Friend")
print(a1)
print(a2)
y=(int(input("Please select a number: ")))
if y==1:
f=(input("Please enter the first name: "))
l=(input("Please enter the last name: "))
p=(input("Please enter the phone number: "))
new=Person(f, l, p)
elif y==2:
f=(input("Please enter the first name: "))
l=(input("Please enter the last name: "))
p=(input("Please enter the phone number: "))
e=(input("Please enter the email address: "))
b=(input("Please enter the birth date in m/d/year format: "))
new=Friend(f, l, p, e, b)
elif x==2:
w=(input("Please enter the last name of the contact you wish to view: "))
w=Person.get_info(w)
elif x==3:
exitprogram=True
main()
答案 0 :(得分:1)
如果你使它们可迭代,那么这些类是可迭代的,但这对你没有帮助。你需要保留一份人员名单:
people = []
当你创建一个新人时,将它们添加到列表中:
person = Person(firstname, lastname, phone)
people.append(person)
现在,您可以搜索人员列表:
def search(people, lastname):
for person in people:
if person.lastname == lastname:
return person
return False
答案 1 :(得分:1)
您需要将联系人存储在列表中。例如:
contacts = []
# To add a contact:
contacts.append(Person(...))
如果你这样做,当然,你可以像任何其他列表一样遍历它:
for person in contacts:
if person.last_name == requested_last_name:
person.get_info()