Nov-27-2017, 06:23 PM
(This post was last modified: Nov-27-2017, 06:23 PM by QueenSvetlana.)
from copy import deepcopy class Book: def __init__(self, book_title, authors): self.book_title = book_title self.authors = deepcopy(authors) self.logs = [] def update_logs(self, log): self.logs.append(log)[b][/b]I have a Book class, with a
self.logs = []
, the utility I'm creating helps people keep notes of the book they are currently reading. Now for learning purposes, I intend to keep this class immutable, it's meant for a book that the user bought, so I don't see how it could change(updating and re-printing the book is another matter, for my simple program, it's not a problem).When modelling data that is really mutable(in my case, the logs), I've seen patterns where it updates the mutable data and returns an object reflecting the change.
In my case, it's only the list that needs updating, how would I go about keeping the list immutable?
What I tried:
class Book: def __init__(self, book_title, authors): self.book_title = book_title self.authors = deepcopy(authors) self._internal_logs = [] self.logs = [] @property def get_logs(self): return deepcopy(self._internal_logs) def update_logs(self, log): self.logs.append(log) self._internal_logs = deepcopy(self.logs)Questions:
- If you wanted to keep an a list immutable, is this the best way to do it?, If not, how?
- When creating the list(
self.logs = []
), I do so in the constructor, the client code doesn't pass a list(IMO, they shouldn't, because no logs have been written yet), is this considered bad practice? Should I allow them to pass in an empty list? For example, the user may create a book file, but they haven't started reading the book yet. This means a book object is created without the logs.