如何修复我的电话簿代码?

时间:2017-04-29 16:04:43

标签: python class initialization

我正在制作一个电话簿代码,可以添加,删除特定的电话号码,启动电话簿并打印电话簿中的所有内容。

class contact:
name=""
number=""
def print_n(self):
    print("name : ", self.name)
    print("number : ",self.number)
def add():            #This is supposed to add names and numbers to contact
name = input("Name: ")
number = input("Number: ")
def init():          #This is supposed to initalize contact
 del contact
def s_delete():    #This is supposed to delete a phonenumber by typing in the person's name
s=input("name: ")
ss=input("number: ")
with contact:
    del s
    del ss
def print_all():    #This is supposed to print every phonenumber in the phonebook
print (contact)
到目前为止,我已经走了多远。我的代码中有什么问题吗?因为它不打印电话簿,也不添加或删除任何电话号码。

1 个答案:

答案 0 :(得分:0)

您的代码不是正确的python。班级"联系" (python类的大写字母为大写,后跟(object)未正确声明,init()应该看起来像__init__等。

此代码是否适合您:

class Phonebook(object):

    def print_n(self, name):
        print("%s: %s" % (name, self.contacts.get(name, "Does not exist")))


    #This is supposed to add names and numbers to contact
    def add(self, name, number): 
        self.contacts[name] = number

    #This is supposed to initalize contact
    def __init__(self):
        self.contacts = {}

    #This is supposed to delete a phonenumber by typing in the person's name
    def s_delete(self, name):
        del self.contacts[name]

    #This is supposed to print every phonenumber in the phonebook
    def print_all(self):
        for name in sorted(self.contacts.keys()):
        print('%s: %s' % (name, self.contacts[name]))


if __name__ == '__main__':
    while True:
    action = input("Action (--add, -a; --delete, -d; --printall, -p; --exit, -e): ")
    if action in ['--add', '-a']:
        name = input("Name: ")
        number = input("Number: ")
        phonebook.add(name, number)
    elif action in ['--delete', '-d']:
        name = input("Name: ")
        phonebook.s_delete(name)
    elif action in ['--printall', '-p']:
        phonebook.print_all()
    elif action in ['--exit', '-e']:
        break
    else:
        print("Unknown action.")
相关问题