Question

I understand how it works and I understand meaning of syntax. But I do not understand why would I want to use it?

Was it helpful?

Solution

There are no private members, including methods, in Python. The double underscore prefix is actually just a “convention” for private members which is additionally inforced by Python as the names are further mangled. It’s not impossible to access these methods from the outside though.

In general though, there is no real need to make members really “private”. Often, a single underscore prefix is used to mark members as “internal”, and users of the types are asked to keep them alone.

Other than that, of course the reason to still have private (or internal) methods would be to extract common parts of functionality into a method so you don’t have to repeat yourself.

For more information on the missing private-ness of Python members, see this question.

OTHER TIPS

sLet's say you have operation operationA that calls to subOperationA and suboperationB on the same class, and those methods have no meaning as individual operations, they manipulate data and you have to prevent unexpected executions of them (that means calls from methods others than operationA). So private allows you to protect and encapsulate your methods, limiting their visibility only to the desired scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top