0

After working a lot with swift, I got used to the following syntax:

private var __privateVar = 100 // Not accessible from outside the Class
public var public_var: Int = {
    return __privateVar // Returns __privateVar, and is get-only variable
}

Is there a way to reproduce this in python 3? Thanks a lot

timbre timbre
  • 12,648
  • 10
  • 46
  • 77
Vipera74
  • 227
  • 3
  • 17

1 Answers1

1

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.

osuka_
  • 484
  • 5
  • 15