相关疑难解决方法(0)

Python改变类变量

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

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的东西).

python variables class

5
推荐指数
1
解决办法
3万
查看次数

类变量和实例变量之间的区别

我已经在Stack Exchange上阅读了很多像Python一样的答案- 为什么在课堂上使用"self"? 阅读完这些内容之后,我了解到实例变量对于类的每个实例都是唯一的,而类变量是在所有实例之间共享的.在玩的时候我发现这个代码 -

class A:
    x = []
    def add(self):
        self.x.append(1)

x = A()
y = A()
x.add()
print "Y's x:",y.x
Run Code Online (Sandbox Code Playgroud)

确实给出了输出[1].但是,这段代码 -

class A:
    x = 10
    def add(self):
        self.x += 1

x = A()
y = A()
x.add()

print "Y's x:",y.x
Run Code Online (Sandbox Code Playgroud)

给出输出,就像10我认为的那样11.如果这是一个非常无聊的问题,请原谅我,但我在编程方面不是很有经验.

python oop class

4
推荐指数
1
解决办法
2454
查看次数

标签 统计

class ×2

python ×2

oop ×1

variables ×1