6

I have someting like this

class A:
  __a = 0
  def __init__(self):
    A.__a = A.__a + 1
  def a(self):
    return A.__a

class B(A):
  def __init__(self):
    # how can I access / modify A.__a here?
    A.__a = A.__a + 1 # does not work
  def a(self):
    return A.__a

Can I access the __a class variable in B? It's possible writing a instead of __a, is this the only way? (I guess the answer might be rather short: yes :)

2
  • 1
    What is your reason for using the double underscore attribute name? Is one underscore not sufficient - used to indicate a 'private' attribute? Commented Jun 18, 2010 at 14:53
  • Well, that's something for a Python expert to answer... Commented Jun 18, 2010 at 18:07

3 Answers 3

11

So, __a isn't a static variable, it's a class variable. And because of the double leading underscore, it's a name mangled variable. That is, to make it pseudo-private, it's been automagically renamed to _<classname>__<variablename> instead of __<variablename>. It can still be accessed by instances of that class only as __<variablename>, subclasses don't get this special treatment.

I would recommend that you not use the double leading underscore, just a single underscore to (a) mark that it is private, and (b) to avoid the name mangling.

Sign up to request clarification or add additional context in comments.

Comments

3

Refer to it as A._A__a. In Python, symbols with a __ prefix occurring inside a class definition are prefixed with _<class-name> to make them somewhat "private". Thus the reference A.__a that appears in the definition of B is, counterintuitively, a reference to A._B__a:

>>> class Foo(object): _Bar__a = 42
... 
>>> class Bar(object): a = Foo.__a
... 
>>> Bar.a
42

Comments

1

There are Python decorators @staticmethod and @classmethod, which you can use to declare a method static or class-related. This should help accessing your class data element:

class MyClass:
     __a = 0

     @staticmethod
     def getA():
         return MyClass.__a

class MyOtherClass:

     def DoSomething(self):
         print MyClass.getA() + 1

Example inspired by this source: http://www.rexx.com/~dkuhlman/python_101/python_101.html

3 Comments

Should be def getA(): return A.__a
Oops, true. Will correct. Also note that in my example class name is MyClass. ;)
Oops, I guess I like piling mistakes on top of mistakes... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.