在Python中访问父类的静态类变量 [英] Access static class variable of parent class in Python
问题描述
我喜欢这样
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
我可以在 B
中访问 __ a
类变量吗?可以写 a
而不是 __ a
,这是唯一的方法吗? (我猜答案可能很短:是的)。
Can I access the __a
class variable in B
? It's possible writing a
instead of __a
, is this the only way? (I guess the answer might be rather short: yes :)
推荐答案
所以, __ a
不是 static 变量,它是一个类变量。并且由于双重前导下划线,它是名称损坏变量。也就是说,为了使其成为伪私有,它已被自动重命名为 _< classname> __< variablename>
而不是 __< variablename>
。它仍然可以被的实例访问只作为 __< variablename>
,子类不会得到这种特殊处理。
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 _<classname>__<variablename>
instead of __<variablename>
. It can still be accessed by instances of that class only as __<variablename>
, subclasses don't get this special treatment.
我建议您不要使用双前导下划线,只使用一个下划线来(a)标记它是私有的,以及(b)避免名称重整。
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.
这篇关于在Python中访问父类的静态类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!