Python – When to use private methods in Python

classpython

I have a class, but every method in it should be private (apart form __init__ and __str__). Should I denote every method with a double underscore, or is that deemed bad practice?

Best Answer

True private methods - those that can't be seen or used from outside of a class - do not exist in Python. What we have are conventions that are merely suggestions to not touch things you shouldn't.

The closest you get to privacy is name mangling. An attribute of MyClass named __some_attr will just be renamed to _MyClass__some_attr internally, making it slightly awkward to reference it from outside the class. This is seldom used. What most people do is simply prefix a single underscore (_attr) as a notation that something should not be relied upon & is not part of the public interface.

Using double underscores before and after the identifier, while not prohibited, is considered reserved for internal language details (like 'magic' methods). You shouldn't go around coming up with new __attr__s (unless you're hacking on the interpreter).