0

Sometimes I see classes that has attributes or methods that start with underscore. Why do they do that?

For example: in Tensorflow, a model class has ._layers and .layers methods.

Alex
  • 599
  • 1
  • 5
  • 14
  • 1
    Possible duplicate of [Python "private" function coding convention](https://stackoverflow.com/questions/15047122/python-private-function-coding-convention) – abc Jun 19 '19 at 23:09

1 Answers1

1

Python has no notion of private members, so underscore is used as a convention to denote private methods or fields.

The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8.

Link for the above quote

Sıddık Açıl
  • 957
  • 8
  • 18
  • But they do the same functionality. I still dont't understand what you mean by private. – Alex Jun 19 '19 at 23:11
  • Does this mean that it is not safe to use them? – Alex Jun 19 '19 at 23:13
  • 3
    @Alex it means that it is for internal use of the package. You as the client of the package are expected to just ignore it and bad things can happen if you use it. If you want to know more (but you don't!) look at the source code. – Stop harming Monica Jun 19 '19 at 23:15
  • As @Goyo mentioned, it may or may not be safe to use them. As a programmer, most of the time you want to hide your implementation details and offer a succinct interface to your client for him/her to work with. For example, you have a Tree class with a postorder_traverse method and an _rec_postorder_traverse method. The first method by convention interfaces with the client of your code whereas the second one does the heavy lifting by performing recursive traversal on your tree. A client is not interested how you recurse on that tree. So, you hide your internal method with an underscore. – Sıddık Açıl Jun 19 '19 at 23:29