37,743
社区成员




>>> class T():
__h = 0
def __init__(self):
self.__h = self.__h + 1
print(self.__h)
>>> T.__dict__
mappingproxy({'__module__': '__main__', '_T__h': 0, '__init__': <function T.__init__ at 0x0000000001D33E18>, '__dict__': <attribute '__dict__' of 'T' objects>, '__weakref__': <attribute '__weakref__' of 'T' objects>, '__doc__': None})
>>> id(T._T__h)
1499448976
>>> t1 = T()
1
>>> t1.__dict__
{'_T__h': 1}
>>> T._T__h
0
>>> T._T__h = 5
>>> t2 = T()
6
>>> t2._T__h
6
>>>
那么要实现期望的那种每新建一个实例,实现变量值累加也是可以的。
例如楼上同学直接使用类名引用类变量来做所有实例共享累加。
另外一个方法,就是要利用可变对象传引用,可以原地修改值的特性。
再来一个例子
>>> class T:
h = [0]
def __init__(self):
self.h[0] = self.h[0] + 1
print(self.h[0])
>>> id(T.h)
48528136
>>> t1 = T()
1
>>> id(t1.h)
48528136
>>> t2 = T()
2
>>> id(t2.h)
48528136
>>> t3 = T()
3
>>> id(t3.h)
48528136
>>>
class Bar(object):
i = 0
j = []
def __init__(self):
Bar.i += 1
print Bar.i
for i in range(5):
Bar()
1
2
3
4
5class Bar(object):
i = 0
j = []
print id(i)
print id(j)
def __init__(self):
print id(self.i)
print id(self.j)
self.i += 1
self.j.append(1)
print id(self.i)
print id(self.j)
Bar()
"""
140435923163024
4406753688
140435923163024
4406753688
140435923163000
4406753688
"""
这是因为python的传值特性(call by sharing)
如果你清楚id函数代表的是什么意思的话,你可以清晰的看出,修改i的值时,会改变其id,修改j的值其id始终不变
其实对所有不可变类型和可变类型,都是一样的,这也是python区别于call by value 和call by reference的一个特性