notebook.py
importdatetime
last_id=0classNote:'''Represent a note in the notebook. Match against a
string in searches and store tags for each note.'''
def __init__(self, memo, tags=''):
self.memo=memo
self.tags=tags
self.creation_date=datetime.date.today()globallast_id
last_id+= 1self.id=last_iddefmatch(self, filter):return filter in self.memo or filter inself.tagsclassNotebook:'''Represent a collection of notes that can be tagged,
modified, and searched.'''
def __init__(self):'''Initialize a notebook with an empty list.'''self.notes=[]def new_note(self, memo, tags=''):'''Create a new note and add it to the list.'''self.notes.append(Note(memo, tags))def_find_note(self, note_id):'''Locate the note with the given id.'''
for note inself.notes:if note.id ==note_id:returnnotereturnNonedefmodify_memo(self, note_id, memo):'''Find the note with the given id and change its
memo to the given value.'''self._find_note(note_id).memo=memodefmodify_tags(self, note_id, tags):'''Find the note with the given id and change its
tags to the given value.'''self._find_note(note_id).tags=tagsdefsearch(self, filter):'''Find all notes that match the given filter
string.'''
return [note for note in self.notes ifnote.match(filter)]
note_book_test.py
from notebook importNote, Notebookdefdisplay_notes(notes):for note innotes:print("Id: %d" %(note.id))print("Memo: %s" %(note.memo))print("------------------------------------------")
n=Notebook()
n.new_note("hello world")
n.new_note("hello again")print(n.notes)
display_notes(n.notes)print("********************************************")print("search keyword: hello")
search_notes= n.search("hello")
display_notes(search_notes)print("********************************************")print("********************************************")print("search keyword: world")
search_notes= n.search("world")
display_notes(search_notes)print("********************************************")print("********************************************")print("after modify note 1:")
n.modify_memo(1, "Hi Master HaKu")
display_notes(n.notes)print("********************************************")
运行结果:
[, ]
Id: 1
Memo: hello world
------------------------------------------
Id: 2
Memo: hello again
------------------------------------------
********************************************
search keyword: hello
Id: 1
Memo: hello world
------------------------------------------
Id: 2
Memo: hello again
------------------------------------------
********************************************
********************************************
search keyword: world
Id: 1
Memo: hello world
------------------------------------------
********************************************
********************************************
after modify note 1:
Id: 1
Memo: Hi Master HaKu
------------------------------------------
Id: 2
Memo: hello again
------------------------------------------
********************************************