Python更改类变量 [英] Python changing class variables
问题描述
好吧,这次我会尝试并非常清楚。
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
现在,在运行时:
Yes().yes()
No().no()
Yes().yes()
No().no()
我要打印出来:
Yes
No
No, but yes
Yes, but no
它给我:
Yes
No
Yes
No
现在,我知道原因是因为我只更改了Self.a的值无课(备注那条线?)。我想知道是否仍然可以在Yes类中同时在No类中对其进行更改(例如是否可以代替self.a- = 1插入某些东西,这样还是可以的)。
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).
推荐答案
我不确定您有什么可能的用途,但是...
I'm not sure what possible use you have for this, but...
您要操作 class 变量,但是您要继续寻址实例变量。如果需要类变量,请使用类变量!
You want to manipulate a class variable, 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
这篇关于Python更改类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!