Member-only story
Private, “Protected” Attributes in Python — Demystified Once and For All
All there is to know about private and “protected” attributes in 748 words
Never, ever use two leading underscores. This is annoyingly private. — Ian Bicking, Creator of pip, virtualenv, and many others
How many times have you encountered these words: Public, Private, and Protected in the world of Python? And how many times those one leading underscores _
, two leading underscores __
puzzled you, trying to make sense of them?
Well, let’s demystify them once and for all. What’s the use of private and “protected” attributes. And, how they look like in the Python world.
What’s The Point of A Private Attribute Anyway?
Consider this scenario: You have a class named Vehicle
which internally uses an instance attribute named horn and does not want to expose it. Now, you want to subclass Vehicle
and name your own class MyCar.
If you create your own horn
instance attribute inside the class MyCar
you will be overriding the Vehicle
’s horn
instance attribute. What happens as a consequence is that you will smash all those methods in Vehicle
class that…