如果类中有列表,实例化类的时候,不同实例中列表是指向相同的列表空间,例如:

# -*- coding: utf-8 -*-
import copy
class test():
    name = {
        'key1':['a', 'b', 'c'],
        'key2':['1', '2', '3']
    }

if __name__ == '__main__':
    z1 = test()
    z2 = test()
    z1.name['key1'][1] = 'zcc'
    z2.name['key1'][1] = 'zzh'
    print z1.name
    print z2.name

运行结果:

{'key2': ['1', '2', '3'], 'key1': ['a', 'zzh', 'c']}
{'key2': ['1', '2', '3'], 'key1': ['a', 'zzh', 'c']}

想要的结果是:z1.name['key1'][1] = 'zcc'  z2.name['key1'][1] = 'zzh'

实际的结果是:全部都设置成了zzh,此时需要对类中的列表做深拷贝。

====================================================

# -*- coding: utf-8 -*-
import copy
class test():
    name = {
        'key1':['a', 'b', 'c'],
        'key2':['1', '2', '3']
    }

if __name__ == '__main__':
    z1 = test()
    z2 = test()
    z1.name = copy.deepcopy(test.name)
    z2.name = copy.deepcopy(test.name)
    z1.name['key1'][1] = 'zcc'
    z2.name['key1'][1] = 'zzh'
    print z1.name
    print z2.name

运行的结果:

{'key2': ['1', '2', '3'], 'key1': ['a', 'zcc', 'c']}
{'key2': ['1', '2', '3'], 'key1': ['a', 'zzh', 'c']}