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

5

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To be clear, _var is not read only and can still be viewed or modified by users.
@Alexanderthat should be clear enough from the very first sentence in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.