Accessing a parent class's static class variable in Python

I have one 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 class variable __ain B? Is it possible to write ainstead __a, is this the only way? (I think the answer can be quite short: yes :)

+3
source share
3 answers

, __a , . - , . , -, _<classname>__<variablename> __<variablename>. - __<variablename>, .

, , , (a) , , (b) .

+7

A._A__a. Python __, , _<class-name>, "private" . , A.__a, B, A._B__a:

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

There are Python @staticmethodand decoders @classmethodthat can be used to declare a static or class method. This should help access the data element of the class:

class MyClass:
     __a = 0

     @staticmethod
     def getA():
         return MyClass.__a

class MyOtherClass:

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

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

+1
source

Source: https://habr.com/ru/post/1750684/


All Articles