Python 更改类变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15790493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:01:03  来源:igfitidea点击:

Python changing class variables

pythonclassvariables

提问by user2154113

Okay, I'll try and be extremely clear this time.

好的,这次我会尽量说清楚。

class Yes:

    def __init__(self):
        self.a=1

    def yes(self):
        if self.a==1:
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if self.a==1:
            print "No"
        else:
            print "Yes, but no"
        self.a-=1 #Note this line

Now, while running:

现在,在运行时:

Yes().yes()
No().no()
Yes().yes()
No().no()

I want it to print out:

我希望它打印出来:

Yes
No
No, but yes
Yes, but no

It gives me:

它给了我:

Yes
No
Yes
No

Now, I know the reason why is because I'm only changing the value of Self.a in the No class(Remember that line?). I want to know if there is anyway to change it in the Yes class while still in the No class (like if there was something that I could plug in in place of the self.a-=1 that would work).

现在,我知道原因是因为我只是在 No 类中更改 Self.a 的值(还记得那行吗?)。我想知道是否有任何方式在 Yes 类中更改它,而仍然在 No 类中(就像我可以插入一些东西来代替 self.a-=1 可以工作)。

采纳答案by Francis Avila

I'm not sure what possible use you have for this, but...

我不确定你有什么可能的用途,但是......

You want to manipulate a classvariable, but you keep addressing instance variables. If you want a class variable, use a class variable!

你想操作一个变量,但你一直在处理实例变量。如果你想要一个类变量,使用一个类变量!

class Yes:
    a = 1 # initialize class var.
    def __init__(self):
        self.a = 1 # point of this is what?

    def yes(self):
        if Yes.a==1: # check class var
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if Yes.a==1: # check class var
            print "No"
        else:
            print "Yes, but no"
        Yes.a-=1 # alter class var

回答by Jesse Vogt

It appears what you want to use is a static variable rather than an instance variable. A static variable is shared between all the instances of the class.

看来您要使用的是静态变量而不是实例变量。静态变量在类的所有实例之间共享。

class Yes:
    a = 1
    def __init__(self):
        pass

    def yes(self):
        if Yes.a==1:
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if Yes.a==1:
            print "No"
        else:
            print "Yes, but no"
        Yes.a-=1 #Note this line

Yes().yes()
No().no()
Yes().yes()
No().no()

Will output:

将输出:

Yes
No
No, but yes
Yes, but no