对 python 中的静态 class 变量感到困惑
Confused about static class vars in python
这里有一些示例代码:
class A:
staticvar=3;
def foo2(self):
print("------ Foo2")
print("static: "+str(A.staticvar));
print("instance: "+ str(self.staticvar));
class B(A):
def setStaticVar(self, num):
B.staticvar=num;
a=A();
b=B();
a.staticvar=7;
a.foo2();
b.setStaticVar(100);
a.foo2();
b.foo2();
结果是:
------
static: 3
instance: 7 -->correct. Instance var modified
------
static: 3
instance: 7 --> Not correct. Why static var is not 100
------
static: 3
instance: 100 --> Correct, but this value should be shared between A and B
为什么会这样?静态变量不应该在 A 和 B 之间共享吗?为什么在b中修改时通过b.
从这个例子看来,每个 class 都有自己的静态变量(从我的角度来看并不是真正的静态变量,因为只有一个静态变量而我们有 2 个,每个 class).
谁能解释一下这种行为?
干杯。
我怀疑您 运行 遇到的是名称解析问题。当你得到 B.staticvar
时,解释器无法找到它并返回到它的超级 classes 来尝试解析名称。遍历 A
后,解释器找到 staticvar
和 returns 的值。
但是,当您将值设置为 B.staticvar
时,您会得到与 "instance" 情况大致相同的行为,其中 new 属性 称为 staticvar
被添加到 B
。现在,当它尝试在 B
(或其实例)上解析 属性 名称时,它会使用这个新值而不会回退到 A
。在 Python 中,继承 class 与共享其属性无关,它是关于设置回退 class 来解析未在 child 中定义的名称 class(因此,为什么不需要显式 "override" 方法,以及如果您希望 parent 函数成为 运行).
要获得您要求的行为,请在 A
中定义 setStaticVar
,and/or 将其主体更改为 A.staticvar=num
这里有一些示例代码:
class A:
staticvar=3;
def foo2(self):
print("------ Foo2")
print("static: "+str(A.staticvar));
print("instance: "+ str(self.staticvar));
class B(A):
def setStaticVar(self, num):
B.staticvar=num;
a=A();
b=B();
a.staticvar=7;
a.foo2();
b.setStaticVar(100);
a.foo2();
b.foo2();
结果是:
------
static: 3
instance: 7 -->correct. Instance var modified
------
static: 3
instance: 7 --> Not correct. Why static var is not 100
------
static: 3
instance: 100 --> Correct, but this value should be shared between A and B
为什么会这样?静态变量不应该在 A 和 B 之间共享吗?为什么在b中修改时通过b.
从这个例子看来,每个 class 都有自己的静态变量(从我的角度来看并不是真正的静态变量,因为只有一个静态变量而我们有 2 个,每个 class).
谁能解释一下这种行为?
干杯。
我怀疑您 运行 遇到的是名称解析问题。当你得到 B.staticvar
时,解释器无法找到它并返回到它的超级 classes 来尝试解析名称。遍历 A
后,解释器找到 staticvar
和 returns 的值。
但是,当您将值设置为 B.staticvar
时,您会得到与 "instance" 情况大致相同的行为,其中 new 属性 称为 staticvar
被添加到 B
。现在,当它尝试在 B
(或其实例)上解析 属性 名称时,它会使用这个新值而不会回退到 A
。在 Python 中,继承 class 与共享其属性无关,它是关于设置回退 class 来解析未在 child 中定义的名称 class(因此,为什么不需要显式 "override" 方法,以及如果您希望 parent 函数成为 运行).
要获得您要求的行为,请在 A
中定义 setStaticVar
,and/or 将其主体更改为 A.staticvar=num