Skip to content
Advertisement

Python “protected” attributes

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

Advertisement

Answer

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.
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement