Python 如何从菜单在类内搜索或从菜单添加到类
我正在用python创建一个电话簿,在如何在类中搜索特定联系人或如何在类中搜索特定条目方面遇到了难题 这就是我到目前为止所做的:Python 如何从菜单在类内搜索或从菜单添加到类,python,class,Python,Class,我正在用python创建一个电话簿,在如何在类中搜索特定联系人或如何在类中搜索特定条目方面遇到了难题 这就是我到目前为止所做的: class person: def __init__(self, first_name, last_name, phone_number): person.first = first_name person_last = last_name person_number = phone_number class
class person:
def __init__(self, first_name, last_name, phone_number):
person.first = first_name
person_last = last_name
person_number = phone_number
class friend:
def __init__(self, email, birth_date):
email = johnny.seagraves8219
birth_date = 8/13/1993
super(friend, self)._init_
ans = True
while ans:
print("""
1. Add a contact
2. Look up contact by name
Press enter to quit
""")
ans = input("What would you like to do?")
if ans == "1":
elif ans == "2":
look_up = input("Who would you like to look up?")
据我所知,该类将没有您可以搜索的条目。该类基本上只是一个构造函数,用于创建电话簿中某个人的实例。可以使用数组保存实例,然后搜索该数组
for i in arrayName:
if(arrayName[i].first == look_up):
# do something
要创建实例,只需调用构造函数:
firstPerson = person("Mike", "Ryans", "1800838699")
arrayName.append(firstPerson)
我对python的知识相当有限,但我认为这应该是可行的。
祝你好运 首先,Flexicon是正确的:您的person/friend类只是一个实体,只保存单个person信息。为了能够搜索人物,您需要创建一个person对象的数组(列表),一个映射名称或昵称到对象的映射(字典)(因此
{'Timmie':}
,或者您可以将其中一种方法封装在地址簿
类中,该类包含基本数据结构之一无法为您提供的其他方法
其他一些重要问题:您的friend类没有扩展person,类的构造函数有两个下划线,如\uuuu init\uuuu
;此外,您应该在person
类中添加电子邮件和出生日期的默认值,否则稍后尝试访问这些值将导致错误;您的属性需要self
bef删除它们,否则它们将不会被视为对象的属性
下面是一种面向对象(使用列表来容纳人员)的方法,尽管对于这样简单的事情来说可能有些过分:
class person:
def __init__(self, first_name, last_name, phone_number):
self.person.first = first_name
self.person_last = last_name
self.person_number = phone_number
self.email = None #Notice the placeholders?
self.birth_date #Not having this information should not be exceptional
class friend(person): #Here, friend extends person
def __init__(self, email, birth_date):
self.email = email
self.birth_date = birth_date
super(friend, self).__init__()
class AddressBook:
def __init__(self, people = None):
if people:
self.entries = list(people)
else:
self.entries = []
#This is merely an example method, a better way would be to use some relational method like SQL to put in a query to find specific information about the person, but that is beyond the scope of this answer
def find_num(self, first_name, last_name):
for person in self.entries:
if (person.last_name, person.first_name) == (last_name, first_name):
return person
return None
哇,谢谢你帮我澄清这一点,我对此感到非常困惑。@user3106067如果你想接受我的答案,只需点击我答案分数下方的绿色复选框:)