How to create class field [list] read-only in python?

I have self.some_field = [] in my class.
I ask, is there a way to make this list read-only, as a property?

+3
source share
2 answers

You need to do this, indeed, a property ...: for example, in __init__

self._some_field = []

and then in class:

@property
def some_field(self):
    return self._some_field

Note that this means that it does not make the list itself immutable: what happens with an error is an assignment, for example,

self.some_field = 'bah'

not a mutator call for example

self.some_field.append('blah')

, ( ) - - (), .

+7

, . , , .

+1

Source: https://habr.com/ru/post/1755164/


All Articles