Python改变类变量

use*_*113 5 python variables class

好的,这次我会非常清楚.

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
Run Code Online (Sandbox Code Playgroud)

现在,在运行时:

Yes().yes()
No().no()
Yes().yes()
No().no()
Run Code Online (Sandbox Code Playgroud)

我希望它打印出来:

Yes
No
No, but yes
Yes, but no
Run Code Online (Sandbox Code Playgroud)

它给了我:

Yes
No
Yes
No
Run Code Online (Sandbox Code Playgroud)

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

Fra*_*ila 14

我不确定你对此有什么用处,但......

您想要操纵变量,但是您要继续寻址实例变量.如果你想要一个类变量,请使用类变量!

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
Run Code Online (Sandbox Code Playgroud)

  • 像这样使用类变量似乎是代码异味。你确定你正在做的事情不能以其他方式完成吗? (3认同)