Python 如何修复我的电话簿代码?
我正在制作一个电话簿代码,可以添加、删除特定的电话号码、初始化电话簿并打印电话簿中的所有内容Python 如何修复我的电话簿代码?,python,class,initialization,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 = i
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)
这就是我到目前为止所做的。我的代码有问题吗?因为它不会打印电话簿,也不会添加或删除任何电话号码 您的代码不是正确的python。类“contact”(python类的首字母大写,后跟
(object)
)未正确声明,init()应该类似于\uuuu init\uuu
等
此代码是否适用于您:
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.")
去阅读类。你必须首先定义
\uuuu init\uuuuu
。直接的问题是你问题中的缩进。请解决这个问题,因为这是一个大障碍,可以进一步分析代码。def init():#这应该是初始化联系人似乎是一个矛盾的说法,因为
尝试删除联系人吗?另外,init()
与\uuuu init\uuuu
不同。这段代码中有很多问题。你能告诉我我的代码的固定版本吗?那几乎需要重写每一行。你需要去阅读类,以及更广泛的python,才能理解这里的所有问题。我得到一个语法错误:不一致的u电话簿缩进中制表符和空格的se。添加('foo','1234')python要求您使用制表符或4空格作为缩进。如果您混合使用制表符或4空格,则会出现此错误。此处建议的方法是将所有内容退格到行首,然后使用4空格进行缩进,因此最终结果与上面的代码类似。我使用空格编辑了此答案,您的cur中是否有制表符租借代码,@Arkady?你在最初的帖子中缩进不正确。它不应该是制表符。我使用vim并将其设置为用空格替换制表符。也许我在复制代码时把它弄糟了……我不确定不匹配是怎么发生的,这只是一个想法。不过,你最初的代码中没有任何缩进c中的方法lass body,这就是我所做的更改。无论如何,你基本上重写了OP的项目,所以我想他们需要跟踪这个问题,与初始代码的问题相比,这个问题很小。