python新手,求前辈们指导,谢谢·

小耗子先森 2016-09-03 01:09:07

运行错误提示local variable 'PhoneBook' referenced before assignment,这个该如何解决,谢谢各位前辈了。
#!/usr/bin/python
# Filename: myPhoneBook2.py
# -*- coding: utf-8 -*-

import re

class PhoneBook(object):
'''This is a phonebook.

AddContact # Add contacts information
ShowContact # Search names and show contacts
SaveContacts # Save contacts to a TXT archive(storage mode----name: number/number)
LoadContacts # Load contacts from the TXT archives
'''

def __init__(self):
self.contactsDict = {}

def AddContact(self):
while True:
name = raw_input('Please input the name:')
name = name.strip() # the name must include valid string
if name != '':
break
print '***name can\' be NULL'

while True:
number = raw_input('Please input the number:')
number = re.sub(r'\D', '', number)
# if the string is not number, then clear
if number != '':
break
print '***number must be digit'

cover = True # if the contact exists, whether override or not
if self.contactsDict.haskey(name):
print 'the contact must exist.'
self.ShowContact(name)
while True:
control = raw_input('''
enter "c": override the original number
enter "n": save original numbers and storage new numbers
enter "q": exit\n>>>''')
if control.lower() == 'n':
cover = False
break
if control.lower() == 'c':
break
if control.lower() == 'q':
return None
print '***Input Error!'

if cover:
self.contactsDict[name] = number
else:
if number in self.contactsDict[name]:
print '***Number must exist'
else:
self.contactsDict[name] = self.contactDict[name] + '/' + number

def ShowContact(self, name):
print '+++++++++++++++++++++++++++++++++++++'
if self.contactsDict.has_key(name):
print '[contact information]'
print '[name: %s]' % name
numberList = self.contactsDict[name].split('/')
for num in range(len(numberList)):
print '[number: %s]' % (number+1, numberList[num])

else:
print 'contact %s is not found' % name
print '+++++++++++++++++++++++++++++++++++++'

def DeleteNumber(self, name):
if self.contactsDict.has_key(name):
self.ShowContact(name)
number = self.contactsDict[name].split('/')
while True:
print '''
Pleasr input the contacts quene
or enter "a" delete the contact
or enter 'q' exit(not delete)
(warning: if all contacts must be cleared, and also the contact's information.)'''
control = raw_input('>>>')
if control.lower() == 'q':
break
elif control.lower() == 's':
del self.contactsDict[name]
break
elif control.isdigit() and int(control) <= len(number):
del number[int(control)-1]
self.contactsDict[name] = '/'.join(number)
break
else:
print '***Input Error!'

def LoadContacts(self):
try:
PhoneBook = open('PhoneBook.txt', 'a+')
contacts = PhoneBook.read()
if contacts == '':
print '***Phonebook is blank.'
else:
ContactsList = contact.split('\n')
for contact in ContactsList:
if not contact == '':
contact = contact.split('\n')
name = contact[0]
number = contact[1]
self.contactsDict[name] = number
finally:
PhoneBook.close()

self.contactsDict = {line.split(':')[0]: line.split(':')[1] for line in open('PhoneBook.txt', 'a+').readlines()}

def SaveContacts(self):
try:
if self.contactsDict:
PhoneBook = open('PhoneBook.txt', 'w')
for name, number in self.contactsDict.items():
line = name + ':' + number
PhoneBook.write(line)
PhoneBook.write('\n')
else:
print '***Contacts information are not found!'
finally:
PhoneBook.close()


if __name__ == '__main__':
myPhoneBook = PhoneBook()
myPhoneBook.LoadContacts()
try:
while True:
raw_input('enter HUICHE button to contine:')
print '''
-----------------------------------------------
Enter a: Adds a new contact
Enter s: Show all contacts information
Enter d: Delete contacts
Enter q: Exit
-----------------------------------------------'''
control = raw_input('>>>')
if control.lower() == 'a':
myPhoneBook.AddContact()
elif control.lower() == 's':
name = raw_input('Please input the contact you want to find.\n>>>')
myPhoneBook.ShowContact(name)
elif control.lower() == 'd':
name = raw_input('Please input the contacts\' name you want to delete.\n>>>')
myPhoneBook.DeleteNumber(name)
elif control.lower() == 'q':
break
else:
print '***Input Error!'
finally:
myPhoneBook.SaveContacts()



...全文
327 1 打赏 收藏 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
1. PhoneBook 应改成全局变量

def LoadContacts(self):
        global PhoneBook  # 全局变量
        try:
            PhoneBook = open('PhoneBook.txt', 'a+')
            contacts = PhoneBook.read()
            if contacts == '':
                print '***Phonebook is blank.'
            else:
                ContactsList = contact.split('\n')
                for contact in ContactsList:
                    if not contact == '':
                        contact = contact.split('\n')
                        name = contact[0]
                        number = contact[1]
                        self.contactsDict[name] = number
        finally:
            PhoneBook.close()

        self.contactsDict = {line.split(':')[0]: line.split(':')[1] for line in open('PhoneBook.txt', 'a+').readlines()}

    def SaveContacts(self):
        global PhoneBook  # 全局变量
        try:
            if self.contactsDict:
                PhoneBook = open('PhoneBook.txt', 'w')
                for name, number in self.contactsDict.items():
                    line = name + ':' + number
                    PhoneBook.write(line)
                    PhoneBook.write('\n')
            else:
                print '***Contacts information are not found!'
        finally:
            PhoneBook.close()
2. 错误第36行

        if self.contactsDict.haskey(name):
        是has_key 而不是 haskey
        if self.contactsDict.has_key(name):

37,737

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧