tags:

views:

988

answers:

5

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

A: 

It is private. You can't access it.

Yuval A
A: 

Make an accessor method, unless I am missing something:

def get_private_attrib(self):
  return self.__privateWhatever
Chris Cameron
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
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
Also, if it's additional facts that belong in the question, please edit the question and delete this non-answer.
S.Lott
+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