0

我的代码的“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()
4

2 回答 2

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
于 2013-04-29T02:23:07.717 回答
1

您需要将联系人存储在列表中。例如:

contacts = []
# To add a contact:
contacts.append(Person(...))

如果你这样做,当然,你可以像任何其他列表一样循环遍历它:

for person in contacts:
    if person.last_name == requested_last_name:
        person.get_info()
于 2013-04-29T02:23:14.480 回答