Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Does Python have “private” variables in classes?

I'm coming from the Java world and reading Bruce Eckels' Python 3 Patterns, Recipes and Idioms.

While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there.

So for example:

class Simple:
    def __init__(self, s):
        print("inside the simple constructor")
        self.s = s

    def show(self):
        print(self.s)

    def showMsg(self, msg):
        print(msg + ':', self.show())

If that’s true, then any object of class Simple can just change the value of variable s outside of the class.

For example:

if __name__ == "__main__":
    x = Simple("constructor argument")
    x.s = "test15" # this changes the value
    x.show()
    x.showMsg("A message")

In Java, we have been taught about public/private/protected variables. Those keywords make sense because at times you want variables in a class to which no one outside the class has access to.

Why is that not required in Python?

Answer*

Cancel
5
  • I'm going to check out that talk. Is the @property thing part of standard Python, or is it specific to an IDE? Commented Aug 20, 2019 at 6:23
  • Its part of the standard since python 2.6. If you should use an older version, there is still the possibility to use property builtin function, which is available since python 2.2
    – Hatatister
    Commented Aug 21, 2019 at 20:25
  • 1
    Sorry to mention this 4 years later, but it's bugging me . In your last example, when you're writting the setter, I think you wrote meter instead of value.
    – Daniel F.
    Commented Jul 19, 2022 at 23:27
  • You are right. I corrected the error.
    – Hatatister
    Commented Jul 20, 2022 at 6:32
  • 1
    This is the best answer. Java developers often forget what property and modules are for in Python.
    – Alex
    Commented Oct 26, 2022 at 8:48