3

I have come from c++ and java background so, I was curious to know if python provides access specifiers as provided by c++/java. I've seen some code, and this is what I think, __variable ---> private. _variable ----> protected. Correct me if I'm wrong.

Sai Kiran
  • 65
  • 1
  • 3

2 Answers2

3

Python has recommended practices rather than prescriptive ones - so anything with a _ at the start should be left alone by others but is not locked to prevent it. There is however name mangling to make life more interesting for members with a __ at the start - see PEP8.

Of course if others rely on your private data/methods rather then the public API they only have themselves to blame when you change something and their code stops working.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
1

There is no such concept in Python. There are conventions that are used - like the ones Steve mentioned but also others such as calling the first variable of an instance method self.

In addition, for module level imports - there is a way to prevent the default behavior of importing all names from a module. This is done by populating __all__ with a list of names that should be imported (exposed) by default.

However, as with __var and _var it is just a convention (although one that is enforced by Python). It doesn't restrict you though - you can explicitly import any name.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284