在看一本书《PYTHON3 面向对象编程》
内容丰富,作作记录。
notebook.py
__author__ = 'chengang882'import datetime# Store the next available id for all new note last_id = 0class Note(object):"""Represent a note in the notebook. Match against astring in searches and store tags for each note."""def __init__(self, memo, tags=''):"""initialize a note with memo and optionalspace-separated tags. Automatically set the note'screation date and a unique id."""self.memo = memoself.tags = tagsself.creation_date = datetime.date.today()global last_idlast_id += 1self.id = last_iddef match(self, filter):"""Determine if this note matches the filtertext. Return True if it matches, False otherwise.Search is case sensitive and matches both text andtags."""return filter in self.memo or filter in self.tagsclass Notebook(object):def __init__(self):self.notes = []def new_note(self, memo, tags=''):self.notes.append(Note(memo, tags))def _find_note(self, note_id):for note in self.notes:if str(note.id) == str(note_id):return notereturn Nonedef modify_memo(self, note_id, memo):note = self._find_note(note_id)if note:note.memo = memoreturn Truereturn Falsedef modify_tags(self, note_id, tags):self._find_note(note_id).tags = tagsdef search(self, filter):return [note for note in self.notes ifnote.match(filter)]
menu.py
__author__ = 'chengang882'import sys from notebook import Notebook, Noteclass Menu:def __init__(self):self.notebook = Notebook()self.choices = {"1": self.show_notes,"2": self.search_notes,"3": self.add_note,"4": self.modify_note,"5": self.quit}def display_menu(self):print("""Notebook Menu1. Show all Notes2. Search Notes3. Add Note4. Modify Note5. Quit""")def run(self):while True:self.display_menu()choice = raw_input("Enter an option: ")action = self.choices.get(str(choice))if action:action()else:print("{0} is note a valid choice".format(choice))def show_notes(self, notes=None):if not notes:notes = self.notebook.notesfor note in notes:print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))def search_notes(self):filter = raw_input("Search for: ")notes = self.notebook.search(filter)self.show_notes(notes)def add_note(self):memo = raw_input("Enter a memo: ")print(memo)self.notebook.new_note(memo)print("Your note has been added.")def modify_note(self):id = raw_input("Enter a note id: ")memo = raw_input("Enter a memo: ")tags = raw_input("Enter tags: ")if memo:self.notebook.modify_memo(id, memo)if tags:self.notebook.modify_tags(id, tags)def quit(self):print("Thank you for using your notebook today.")sys.exit(0)if __name__ == "__main__":Menu().run()