← Home

Python private

By Брендель В. М.

Так как питон интерпритатор, а не компилятор, реализация private и protected немного через жопная.

Кстати говоря, по хорошему, в текущих реалиях единственный разумный подход использования private и protected — прятать переменные и методы, чтобы поменьше писать документации. Т. е. все публичные методы и переменные должны быть описаны, чтобы поменьше писать их скрывают.

Из StackOverflow в Python делается так:

Python does not have any private variables like C++ or Java does. You could access any member variable at any time if wanted, too. However, you don't need private variables in Python, because in Python it is not bad to expose your classes member variables. If you have the need to encapsulate a member variable, you can do this by using "@property" later on without breaking existing client code.

In python the single underscore "_" is used to indicate, that a method or variable is not considered as part of the public api of a class and that this part of the api could change between different versions. You can use these methods/variables, but your code could break, if you use a newer version of this class.

The double underscore "__" does not mean a "private variable". You use it to define variables which are "class local" and which can not be easily overidden by subclasses. It mangles the variables name.

Хорошая статья с разжевыванием Pythonic way:

https://www.programiz.com/python-programming/property