Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access static class variable of parent class in Python

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 :)

like image 476
fuenfundachtzig Avatar asked Jun 18 '10 14:06

fuenfundachtzig


People also ask

How do you access a static variable in Python?

If the method is an instance method, then we can access the static variable by using the self variable and class name. To access the static variable inside the class method, then we have to use @classmethod decorator and then by using the cls variable or by using classname.

How do you access the variables of Parent class in a Child class in Python?

Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.

How do you access class variables outside class in Python?

If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.

Can we access static variable outside the class?

From outside the class, "static variables should be accessed by calling with class name." From the inside, the class qualification is inferred by the compiler.


2 Answers

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.

like image 123
Matt Anderson Avatar answered Oct 20 '22 08:10

Matt Anderson


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
like image 38
Marcelo Cantos Avatar answered Oct 20 '22 06:10

Marcelo Cantos