What about protected?
And what about protected
access?
In Python, you can indicate that an attribute is protected by prepending it with one underscore, e.g. self._age
.
However, anybody can still access these attributes, whether or not they are subclasses. So the underscore is just a hint to users that this is meant to be a protected or even private attribute, and they should probably not use it.
Rather than trying to secure things to make sure that programmers do not break rules, Python assumes that most programmers are responsible and rational. So if you see someone using your protected attribute inappropriately, feel free to give them a gentle rebuke!
From a software engineering point, you might also reconsider whether you really need protected attributes in the first place. In fact, you can also reconsider whether it might be better to use composition (contain other classes as attributes) or association (using other classes) instead of inheritance. While inheritance is powerful, it also causes a lot of dependency issues between classes, making it hard to extend and maintain. This can actually be reduced by using composition/association instead.