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 :)
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With