Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.1 KiB

  1. import datetime
  2. # Store the next available id for all new notes
  3. last_id = 0
  4. class Note:
  5. '''Represent a note in the notebook. Match against a
  6. string in searches and store tags for each note.'''
  7. def __init__(self, memo, tags=''):
  8. '''initialize a note with memo and optional
  9. space-separated tags. Automatically set the note's
  10. creation date and a unique id.'''
  11. self.memo = memo
  12. self.tags = tags
  13. self.creation_date = datetime.date.today()
  14. global last_id
  15. last_id += 1
  16. self.id = last_id
  17. def match(self, filter):
  18. '''Determine if this note matches the filter
  19. text. Return True if it matches, False otherwise.
  20. Search is case sensitive and matches both text and
  21. tags.'''
  22. return filter in self.memo or filter in self.tags
  23. class Notebook:
  24. '''Represent a collection of notes that can be tagged,
  25. modified, and searched.'''
  26. def __init__(self):
  27. '''Initialize a notebook with an empty list.'''
  28. self.notes = []
  29. def new_note(self, memo, tags=''):
  30. '''Create a new note and add it to the list.'''
  31. self.notes.append(Note(memo, tags))
  32. def modify_memo(self, note_id, memo):
  33. '''Find the note with the given id and change its
  34. memo to the given value.'''
  35. note = self._find_note(note_id)
  36. if note:
  37. note.memo = memo
  38. return True
  39. return False
  40. def modify_tags(self, note_id, tags):
  41. '''Find the note with the given id and change its tags
  42. to the given value.'''
  43. note = self._find_note(note_id)
  44. if note:
  45. note.tags = tags
  46. return True
  47. return False
  48. def search(self, filter):
  49. '''Find all notes that match the given filter string.'''
  50. return [note for note in self.notes if note.match(filter)]
  51. def _find_note(self, note_id):
  52. '''Locate the note with the given id.'''
  53. for note in self.notes:
  54. if str(note.id) == str(note_id):
  55. return note
  56. return None