Access static class variable of parent class in Python

后端 未结 3 2090
闹比i
闹比i 2021-01-06 04:29

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


        
3条回答
  •  梦谈多话
    2021-01-06 04:36

    Refer to it as A._A__a. In Python, symbols with a __ prefix occurring inside a class definition are prefixed with _ 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
    

提交回复
热议问题