我的代码的“get_info”部分遇到了一些麻烦。具体来说,只要我输入 self 部分并且它对应于类中的实例,我的 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()