该函数在search_a_record中调用,然后依次在find_a_record和display_a_record中调用 self .__ records是Contact对象的列表:
:[联系人(John,7589943,john @ amail.com),联系人(Kelly,4344345,kelly @ bmail.com),联系人(Nicky,8774104,nicky @ cmail.com),联系人(Sam,5723943, sam@dmail.com)]
self .__记录中的项目存储为“联系人”对象。
如果该名称在“电话簿”中,则find_a_record函数需要返回“联系人”对象。
我正在遍历对象并比较名称,但出现错误,我在做什么错了?
1. Look up a contact
2. Add a new contact
3. Change an existing contact
4. Delete a contact
5. Display all contacts
6. Quit the program
------------------------------------------------
Enter your choice: 1
------------------------------------------------
Enter the name: John
Traceback (most recent call last):
File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/A1Q1rene001.py", line 91, in <module>
main()
File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/A1Q1rene001.py", line 87, in main
menu(contacts)
File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/A1Q1rene001.py", line 59, in menu
contacts.search_a_record()
File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/PhoneBook.py", line 82, in search_a_record
name = input("Enter the name: ")
File "<string>", line 1, in <module>
NameError: name 'John' is not defined
class Contact:
def __init__(self, name, phone, email):
self.__name = name # the full name
self.__phone = phone # the phone number
self.__email = email # the email address
def get_name(self):
return self.__name
#Finds a record
def find_a_record(self, name):
for contact in self.__records: # type: object
if contact.get_name() == name:
return contact
return None
def display_a_record(self, item):
print("Name:{}".format(item.get_name()))
print("Phone:{}".format(item.get_name()))
print("Email:{}".format(item.get_name()))
# This function searches and displays a contact record.
def search_a_record(self):
name = input("Enter the name: ")
isNameExist = self.find_a_record(name)
if(isNameExist == None):
print("{} is not found in the phone book.".format(name))
else:
self.display_a_record(isNameExist)
<type 'tuple'>: (<type 'exceptions.NameError'>, NameError("name 'John' is not defined",), None)
<type 'list'>: [Contact(John,7589943,john@amail.com), Contact(Kelly,4344345,kelly@bmail.com), Contact(Nicky,8774104,nicky@cmail.com), Contact(Sam,5723943,sam@dmail.com)]
答案 0 :(得分:3)
input([prompt])
:相当于
eval(raw_input(prompt))
。 [...] 考虑将raw_input()
函数用于用户的一般输入。
raw_input([prompt])
:如果存在提示参数,则将其写入标准输出而无需尾随换行符。然后,该函数从输入中读取一行,将其转换为字符串(将尾随换行符分隔),然后将其返回。
因此,您应该在python 2.7中调用input
,而不是调用raw_input
。
通过调用input
,实际上是在尝试执行用户输入的内容,就像执行Python代码一样。例如,在键入John
时,input
函数正在尝试执行代码John
,这就是为什么出现错误name 'John' is not defined
的原因。绝对不是您想要的,这也是一个安全问题。
相反,raw_input
会将用户的John
解释为字符串"John"
。
但是您应该注意raw_input
在python 3中已重命名为input
,因此如果您打算有一天将代码迁移到新版本的python,请务必小心!