larsmans 的回答非常好,但如果我们查看作业前后的id
情况,它可能会提供额外的见解。x.b
class c():
a=[1]
b=1
def __init__(self):
pass
x=c()
print "initial a : {} at {}".format(x.a, id(x.a))
print "initial b : {} at {}".format(x.b, id(x.b))
x.a.append(1)
x.b+=1 # x.b = x.b + 1, created a new object
# we created an instance variable x.b and it
# is shadowing the class variable b.
print "after change a : {} at {}".format(x.a, id(x.a))
print "after change b : {} at {}".format(x.b, id(x.b))
y=c()
# We can already see from the class object that
# b has not changed value
print "in class c b : {} at {}".format(c.b, id(c.b))
print "in instance y a : {} at {}".format(y.a, id(y.a))
print "in instance y b : {} at {}".format(y.b, id(y.b))
结果:
initial a : [1] at 50359040
initial b : 1 at 40974280
after change a : [1, 1] at 50359040
after change b : 2 at 40974256 # Shows id of instance variable x.b; hence it is
# different
in class c b : 1 at 40974280
in instance y a : [1, 1] at 50359040
in instance y b : 1 at 40974280
如果您想使用 anint
作为类变量,这应该有效:
class MyClass(object):
b=1
def increase_b(self, n):
MyClass.b += n
结果:
>>> mc_1 = MyClass()
>>> mc_1.b
1
>>> mc_1.increase_b(5)
>>> mc_1.b
6
>>> mc_2 = MyClass()
>>> mc_2.b
6
>>> mc_2.increase_b(10)
>>> MyClass.b
16
>>> mc_2.b
16
>>> mc_1.b
16