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 :)
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:Example inspired by this source: http://www.rexx.com/~dkuhlman/python_101/python_101.html
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 referenceA.__a
that appears in the definition ofB
is, counterintuitively, a reference toA._B__a
: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.