Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "protected" attributes

Tags:

python

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

like image 897
m2o Avatar asked Apr 28 '09 12:04

m2o


2 Answers

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.
like image 154
Ed. Avatar answered Sep 29 '22 09:09

Ed.


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.

like image 22
Lutz Prechelt Avatar answered Sep 29 '22 08:09

Lutz Prechelt