简体   繁体   中英

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?

You need to make it, indeed, a property...: eg, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM