今天在网上复习了一下python,用的是《简明Python教程》(第四版)。这是一本很好的入门级Python教材,简明扼要,查阅方便。
教材最后的作业是用python编写一个地址簿,可以实现联系人添加、打印、查阅、修改等功能,还要能把整个地址簿保存到文件、从文件读取。
这个作业基本上用到了本书中涉及的所有要点,包括面向对象编程、列表、文件IO等。
以下是我的作业,完成时间大约1小时。
```python
import pickle as p
class Contact:
# 这是一个联系人类,包含姓名、电话、地址三个属性
def __init__(self, name, phone, addr = ""):
self.name = name
self.phone = phone
self.addr = addr
def print(self):
# 打印联系人
print("Name: %s Phone: %s Addr: %s" % (self.name, self.phone, self.addr))
class Abook:
# 这是一个地址簿类
def __init__(self, filename = "C:/Users/yutuo/Documents/Python Scripts/address_book/address_book.data"):
try:
# 首先尝试从指定文件中读取地址簿
f = open(filename, 'rb')
except FileNotFoundError:
# 如果找不到文件,则创建空的联系人列表
self.clist = []
return
try:
self.clist = p.load(f)
except EOFError:
# 如果文件为空,则创建空的联系人列表
self.clist = []
finally:
# 关闭文件
f.close()
def addContact(self, name, phone, addr = ""):
for c in self.clist:
# 首先查找,联系人是否已经存在
if c.name == name:
print("%s already exists." % name)
return
# 创建新的联系人实例
newContact = Contact(name, phone, addr)
# 将新的练习人添加到联系人列表
self.clist.append(newContact)
def countContact(self):
# 打印总的联系人数
print("I have %d contacts." % len(self.clist))
def printContact(self, name):
# 打印指定联系人
for c in self.clist:
if c.name == name:
c.print()
return
print("No contact named %s found." % name)
def printAll(self):
# 打印所有联系人
if len(self.clist) == 0:
print("Zero contact.")
return
for c in self.clist:
c.print()
def editContact(self, name, phone, addr = ""):
# 修改指定联系人信息
for c in self.clist:
if c.name == name:
c.phone = phone
c.addr = addr
print("Contact information changed.")
c.print()
return
print("No contact named %s found." % name)
def delContact(self, name):
# 删除指定联系人
for c in self.clist:
if c.name == name:
self.clist.remove(c)
print("%s removed." % name)
return
print("No contact named %s found." % name)
def closeBook(self, filename = "C:/Users/yutuo/Documents/Python Scripts/address_book/address_book.data"):
# 将地址簿保存到文件,并关闭
f = open(filename, 'wb')
p.dump(self.clist, f)
print("Address book closed. Saved at %s" % filename)
f.close()
```
网友评论