Python doesn't even have the concept of access modifiers - so if you mean you want a private variable, that's not something you can do. You can, however, use a read-only property:
class Test:
def __init__(self):
self._var = 'some string'
@property
def var(self):
return self._var
Then, use it as such:
obj = Test()
obj.var # works
obj.var = 'whatever' # raises AttributeError
obj._var = 'whatever' # still works
It's noteworthy that you can somewhat emulate the behavior of a private variable by prefixing your variable with a double underscore (such as in __var
), which introduces name mangling if used in a class scope. This is not foolproof, though, and you can always get around it if you really want to. Generally, however, Python developers know not to assign to variables starting in one or two underscores.