Access static class variable of parent class in Python

后端 未结 3 2077
闹比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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-06 04:57

    There are Python decorators @staticmethod and @classmethod, which you can use to declare a method static or class-related. This should help accessing your class data element:

    class MyClass:
         __a = 0
    
         @staticmethod
         def getA():
             return MyClass.__a
    
    class MyOtherClass:
    
         def DoSomething(self):
             print MyClass.getA() + 1
    

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

提交回复
热议问题