How do I access a private attribute of a parent class from a subclass (without making it public)?
A:
Make an accessor method, unless I am missing something:
def get_private_attrib(self):
return self.__privateWhatever
Chris Cameron
2009-04-28 12:57:45
A:
Yes I know it private, it private because there is no such thing as protected. Makes sense making a getter, seems the best thing to do...
m2o
2009-04-28 12:59:58
Please do not post replies in answers. This is not an answer. It is a comment. You can comment on Chris Cameron's answer by clicking "add comment" underneath it.
Paolo Bergantino
2009-04-28 13:00:35
Also, if it's additional facts that belong in the question, please edit the question and delete this non-answer.
S.Lott
2009-04-28 13:10:14
+1
A:
if the variable name is "__secret" and the class name is "MyClass" you can access it like this on an instance named "var"
var._MyClass__secret
The convention to suggest/emulate protection is to name it with a leading underscore: self._protected_variable = 10
Of course, anybody can modify it if it really wants.
+9
A:
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.
Ed
2009-04-28 13:03:31