2017-02-02 40 views
-4

这段代码模拟合并2本联系簿。为什么我的程序错误(python)?

我的第18行代码错误没有明显的原因与短语错误。我很确定这个措辞是正确的,程序应该运行,但每次我得到一个短语错误。

class ContactBook: 
     """ 
     This class represents a book of contacts. 
     It can store names and phone numbers. 
     """ 

     def __init__(self): 
     # Create an empty dictionary 
     self.contacts = {} 

    def __repr__(self): 
     # Just print a string version of the dictionary 
     return str(self.contacts) 
    def __add__(self, other): 
     con2 = ContactBook() 
     for name in self.contacts: 
      if name in other.contacts and self.contacts[name] != other.contacts[name]: 
       con2.contacts[name] = self.contacts[name] + " or " + other.contacts[name] 
      else: 
       con2.contacts[name] = self.contacts[name] 
     for name in other.contacts: 
      if name not in self.contacts: 
       con2.contacts[name] = other.contacts[names] 
     return con2 

    def add_contact(self, name, number): 
     # Adds a name --> phone number pair to 
     # the dictionary. 
     self.contacts[name] = number 

############################# 
# Program starts here 

cb1 = ContactBook() 
cb2 = ContactBook() 

cb1.add_contact("Jonathan", "444-555-6666") 
cb1.add_contact("Puneet", "333-555-7777") 
cb2.add_contact("Jonathan", "222-555-8888") 
cb2.add_contact("Lisa", "111-555-9999") 



# The result of this should be a book that 
# looks like this: 
# 
# { 
#  "Jonathan": "444-555-6666 or 222-555-8888", 
#  "Puneet": "333-555-7777", 
#  "Lisa": "111-555-9999" 
# } 
cb3 = cb1 + cb2 
print cb1 
print cb2 
print cb3 
+4

请分享堆栈跟踪与你所得到的错误消息。我从来没有听说过Python中的* Phrase Error *。如果不知道错误,我们将无法为您提供帮助 –

+1

您的__init__缩进不正确 – Mark

+0

纠正拼写错误后适用于我。 – L3viathan

回答

3

我觉得names这里是一个错字:

con2.contacts[name] = other.contacts[names] 
相关问题