Python 使变量对所有子类通用

Python 使变量对所有子类通用,python,Python,我想要一个带有变量a的类temp,以及它的两个子类c1和c2。如果a在c1中更改,则它也应反映在c2中,反之亦然。为此,我尝试: class temp(ABC): a=1 def f(self): pass class c1(temp): def f(self): print(self.a) class c2(temp): def f(self): print(self.a) o1=c1() o2=c2

我想要一个带有变量
a
的类
temp
,以及它的两个子类
c1
c2
。如果
a
c1
中更改,则它也应反映在
c2
中,反之亦然。为此,我尝试:

class temp(ABC):

    a=1

    def f(self):
        pass

class c1(temp):

    def f(self):
        print(self.a)

class c2(temp):

    def f(self):
        print(self.a)

o1=c1()
o2=c2()
o1.f()
o2.f()
o1.a+=1
o1.f()
o2.f()
它给了我输出:

1
1
2
1
我想让它

1
1
2
2

我也尝试了
super.a
而不是
self.a
,但它给了我一个错误。我怎样才能达到预期的目标?谢谢…

您需要增加静态变量本身,而不是增加
o1.a

Ie
温度a+=1

class temp():
    a=1
    def f(self):
        pass

class c1(temp):
    def f(self):
        print(self.a)

class c2(temp):
    def f(self):
        print(self.a)

o1=c1()
o2=c2()
o1.f()
o2.f()
temp.a+=1
o1.f()
o2.f()

>>> 1
    1
    2
    2

他想从OP中更改o1和o2,而不是温度
,如果c1中更改了a,它也应该反映在c2中,反之亦然。
,但你在更新基本分类这听起来可能很愚蠢,但我不知道为什么我没有想到that@DeveshKumarSingh即使我在
c1
中更改了某些内容,我可以改为在
temp
中更改它,因为
c1
是它的子类,那么您可能想改写您的问题!