代码之家  ›  专栏  ›  技术社区  ›  fuenfundachtzig

访问python中父类的静态类变量

  •  3
  • fuenfundachtzig  · 技术社区  · 16 年前

    我有这样的东西

    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
    

    我能进入吗 __a 类变量在 B ?可能是写作 a 而不是 阿雅 ,这是唯一的方法吗?(我想答案可能很短:是的:)

    3 回复  |  直到 16 年前
        1
  •  7
  •   Matt Anderson    16 年前

    所以, __a 不是一个 静止的 变量,它是一个类变量。由于双前导下划线,它是 name mangled 变量。也就是说,为了使其伪私有化,它被自动重命名为 _<classname>__<variablename> 而不是 __<variablename> . 它仍然可以通过 只有那个班级 作为 _<变量名称> ,子类不接受这种特殊处理。

    我建议您不要使用双前导下划线,只使用一个下划线来(a)标记它是私有的,(b)避免名称混淆。

        2
  •  3
  •   Marcelo Cantos    16 年前

    称之为 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
  •  1
  •   Andrei Sosnin    16 年前

    有巨蟒装饰师 @staticmethod @classmethod ,可用于声明方法静态或与类相关。这将有助于访问类数据元素:

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

    受此来源启发的示例: http://www.rexx.com/~dkuhlman/python_101/python_101.html