Python "protected" attributes

How do I access a private attribute of a parent class from a subclass (without making it public)?


My understanding of Python convention is

  • _member is protected
  • __member is private

Options for if you control the parent class

  • Make it protected instead of private since that seems like what you really want
  • Use a getter (@property def _protected_access_to_member...) to limit the protected access

If you don't control it

  • Undo the name mangling. If you dir(object) you will see names something like _Class__member which is what Python does to leading __ to "make it private". There isn't truly private in python. This is probably considered evil.

Two philosophies of protection

Some language designers subscribe to the following assumption:

"Many programmers are irresponsible, dim-witted, or both."

These language designers will feel tempted to protect programmers from each other by introducing a private specifier into their language. Shortly later they recognize that this is often too inflexible and introduce protected as well.

Language designers such as Python's Guido van Rossum, in contrast, assume that programmers are responsible adults and capable of good judgment (perhaps not always, but typically). They find that everybody should be able to access the elements of a program if there is a need to do that, so that the language does not get in the way of doing the right thing. (The only programming language that can reliably get in the way of doing the wrong thing is the NULL language)

Therefore, _myfield in Python means something like "The designer of this module is doing some non-obvious stuff with this attribute, so please do not modify it and stay away from even reading it if you can -- suitable ways to access relevant information have been provided (or so we hope)."

In case you are not able to stay away from accessing _myfield (such as in special cases in a subclass), you simply access it.