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.

88 lines
2.6 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 space-separated tags.
  9. Automatically set the note's creation date and a unique id."""
  10. self.memo = memo
  11. self.tags = tags
  12. self.creation_date = datetime.date.today()
  13. global last_id
  14. last_id += 1
  15. self.id = last_id
  16. def match(self, filter):
  17. """Determine if this note matches the filter text.
  18. Return True if it matches, False otherwise.
  19. Search is case sensitive and matches both text and tags."""
  20. return filter in self.memo or filter in self.tags
  21. class Notebook:
  22. """Represent a collection of notes that can be tagged, modified and
  23. searched."""
  24. def __init__(self):
  25. """Initialize a notebook with an empty list."""
  26. self.notes = []
  27. def new_note(self, memo, tags=''):
  28. """Create a new note and add it to the list."""
  29. self.notes.append(Note(memo, tags))
  30. def modify_memo(self, note_id, memo):
  31. """Find the note with the given id and change its
  32. memo to the given value."""
  33. note = self._find_note(note_id)
  34. if note:
  35. note.memo = memo
  36. return True
  37. return False
  38. def modify_tags(self, note_id, tags):
  39. """Find the note with the given id and change its tags
  40. to the given value."""
  41. note = self._find_note(note_id)
  42. if note:
  43. note.tags = tags
  44. return True
  45. return False
  46. def search(self, filter):
  47. """Find all notes that match the given filter string."""
  48. return [note for note in self.notes if note.match(filter)]
  49. def _find_note(self, note_id):
  50. """Locate the note with the given id."""
  51. for note in self.notes:
  52. if str(note.id) == str(note_id):
  53. return note
  54. return None
  55. def remove_note(self, id):
  56. """Remove note(s) with given id from note list"""
  57. if self._find_note(id):
  58. removed = []
  59. for index, note in enumerate(self.notes):
  60. if str(note.id) == str(id):
  61. removed.append(self.notes.pop(index))
  62. self._set_id()
  63. return removed
  64. return False
  65. def _set_id(self):
  66. """set global last_id to highest id found in notebook"""
  67. id = 1
  68. for note in self.notes:
  69. if note.id > id:
  70. id = note.id
  71. global last_id
  72. last_id = id