I work with python and javascript, and often I see variables, functions or methods in someone else's code that start with an underscore or are wrapped in one or two underscores. On what basis, the developers wrap some methods, and some leave without underscores, I do not understand. Are there any unwritten rules for such registration, or am I poorly reading the documentation?
2 answers
In python:
If a variable begins with a single underscore (_name), then it is a variable intended to be used only inside the object within which it is declared. You can still call it externally by writing object._name
A single underscore is simply an indication that the variable refers to the internal mechanics of the object and it is better not to touch it unnecessarily.
If a variable begins with a double underscore, but does not have underscores at the end (__name), then you will not be able to call this variable from the outside in the usual way object .__ name
However, with the help of a special syntax, you can even get close to it from the outside, but it is not recommended to do so extremely - if the programmer decided to protect the variable with a double underscore, then he probably had reasons to do so.
Names that are wrapped in double underscores are the so-called "magic" or "magic" methods. With their help, some special mechanics of object behavior are realized.
In these languages, it is not possible to make the methods and properties of the class truly private, so the developers have agreed to add to them the prefixes-anderskory. But in some agreements this is intentionally prohibited, for example, in the airbnb agreement .
- oneStrictly speaking you are wrong. When using a specific approach to writing code, this is possible. In javascript , if you make public methods of a class on closures, then for private ones, declare local variables in the body of the constructor. And it seems that this is a fairly common practice in ES 5. In python , this can all be organized, for example, through magic with
__setattr__,__getattr__, for example, something like this: ru.stackoverflow.com/questions/81843/#551736 Or process the methods by names in the metaclass (in the end, too, will be__setattr__,__getattr__). But there is no point in this. - Ilia w495 Nikitin - @ Iliaw495Nikitin, yes, that's exactly what is written in the airbnb guide. Let's just say: there is no simple standard way to make private methods, unlike, for example, Java. Someone wants real privacy and they bother with closures, while someone just needs to mark the "private" entities with an underscore. - Alexey Ukolov