[Tutor] Protected in Python

Alan Gauld alan.gauld at btinternet.com
Mon Apr 16 07:43:02 CEST 2007

"Nader Alrawahi" <nalrawahi at gmail.com> wrote

> in Python. We know that methods can be private or public , but is 
> there a
> way we can make them protected in Python, something similar to Java?

No, Python does not support protected.
However a common conventionis to use a single underscore
before the name to *suggest* that the name should not be directly
accessed, rather like protected attributes.

However IMHO you are far better off working without the type of
data hiding you use in static languages like C++/Java etc.
Embrace the Python idioms and stop worrying about such things
unless you have a very real reason. (Even then I suggest that
using properties is a better solution in most cases). The Python
way is to believe that we are all intelligent programmers and trust

C++ introduced the private/protected/public paranoia into OOP
and unfortunately every language since seems to have followed it.
But such tricks are rarely needed if the class is designed properly
such that the operations do all that is needed. And if they don't
then no amount of "protection" will impriove the situation, it just
makes the class harder to use/reuse. Even C++ didn't introduce
protected till version 2.0...


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list