Access static class variable of parent class in Python

后端 未结 3 2080
闹比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:32

    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 ___ instead of __. It can still be accessed by instances of that class only as __, 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.

提交回复
热议问题