[英]different behavior of strings and numbers in python when dealing with class and object variables
I found one issue and not able to understand the reason of difference: 我发现了一个问题,但无法理解差异的原因:
code1: 代码1:
class Test:
var=2
def __init__(self):
self.var=self.var+1
p=Test()
print "p.var:",p.var
q=Test()
print "q.var:",q.var
output 1: 输出1:
p.var:3
q.var:3
Why not the output is(According to concept used to explain code2) 为什么不是输出(根据用于解释代码2的概念)
p.var:3
q.var:4
Code2: 代码2:
class Test:
var=[]
def __init__(self):
self.var.append("fool")
p=Test()
print "p.var:",p.var
q=Test()
print "q.var:",q.var
output2: 输出2:
p.var: ['fool']
q.var: ['fool', 'fool']
i read the article on code2 in Stack Exchange: python class instance variables and class variables 我在Stack Exchange中阅读了有关code2的文章: python类实例变量和类变量
but not able to link code1 with the following concept.Please help 但无法将code1与以下概念链接。请帮助
The difference here is that lists are mutable objects; 此处的区别在于列表是可变对象; integers are immutable.
整数是不可变的。 When code1 increments self.var, it must return a new object, that being 3. On the second call,we start over with 2, producing another 3 for object q .
当code1递增self.var时,它必须返回一个新对象3。在第二个调用中,我们从2重新开始,为对象q生成另一个3。
In code2, var is still a class object (only one for the class, not one per object). 在code2中, var仍然是一个类对象(该类仅一个,每个对象一个)。 When we create p , we append "fool" to the empty list.
当创建p时 ,我们将“ fool”附加到空列表中。 When we later create q we append a second "fool".
稍后创建q时,我们附加了第二个“傻瓜”。 Print them both:
同时打印它们:
p=Test2()
print "p.var1:",p.var
q=Test2()
print "q.var2:",q.var
print "p.var2:",p.var
output: 输出:
p.var1: ['fool']
q.var2: ['fool', 'fool']
p.var2: ['fool', 'fool']
Does that clarify things? 这样可以澄清事情吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.