How to make a class field [list] read-only in python?
-
i have self.some_field = [] in my class Im enquiring is there a way to make this list read-only like a property?
-
Answer:
You need to make it, indeed, a property...: e.g., in __init__ self._some_field = [] and then later in the class's body: @property def some_field(self): return self._some_field Note that this does not make the list itself immutable: what will fail is an assignment like, say, self.some_field = 'bah' not the call of a mutator, like, say, self.some_field.append('blah') If you want to make the field immutable, it cannot be a list, by definition (since a list is a mutable sequence) -- it must be some other type of sequence (an immutable one) which you need to define for the purpose.
shmakova at Stack Overflow Visit the source
Other answers
If you mean the attribute, then make it a read-only property. If you mean the list itself, then use a tuple instead since they're immutable.
Ignacio Vazquez-Abrams
Related Q & A:
- How to render a radial field in OpenGL?Best solution by Stack Overflow
- How to construct a class diagram?Best solution by sourcemaking.com
- How to disable a sharepoint 2010 list column through sharepoint designer?Best solution by SharePoint
- How to make a list with only images?Best solution by Super User
- How do I make a group contact list?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.