1. Dictionary copy:
dict = {'name':'wang', 'sex':'m', 'age':34, 'job':'it'} info = dict ##Alias (Two dictionaries point to the same address space in memory) info1 = () #shadow copy (the first layer of nested dictionary is independent, and the second layer is related below) import copy () #shadow copy () #deep copy deep copy (completely independent)
Note: The association under shallow copy is only for nested objects contained in the initial state of the dictionary, and the newly added ones will not be added.
example:
>>> dict {'info': ['a', 'b', 1, 2], 'job': 'it', 'sex': 'm', 'age': 40, 'name': 'wang'} >>> dict_alias = dict >>> dict_copy = (dict) >>> dict_deep = (dict)
#Add, change, and delete object key values in the first layer, shallow copy and deep copy are not affected
>>> dict['age'] = 32 >>> del dict['sex'] >>> dict {'info': ['a', 'b', 1, 2], 'job': 'it', 'age': 32, 'name': 'wang'} >>> dict_alias {'info': ['a', 'b', 1, 2], 'job': 'it', 'age': 32, 'name': 'wang'} >>> dict_copy {'info': ['a', 'b', 1, 2], 'job': 'it', 'age': 40, 'name': 'wang', 'sex': 'm'} >>> dict_deep {'info': ['a', 'b', 1, 2], 'job': 'it', 'age': 40, 'name': 'wang', 'sex': 'm'}
#Change or delete the original second layer object key value, shallow copy will be affected, while deep copy will not be affected
>>> dict['info'][2] = 100 >>> dict {'info': ['a', 'b', 100, 2], 'job': 'it', 'age': 32, 'name': 'wang'} >>> dict_alias {'info': ['a', 'b', 100, 2], 'job': 'it', 'age': 32, 'name': 'wang'} >>> dict_copy {'info': ['a', 'b', 100, 2], 'job': 'it', 'age': 40, 'name': 'wang', 'sex': 'm'} >>> dict_deep {'info': ['a', 'b', 1, 2], 'job': 'it', 'age': 40, 'name': 'wang', 'sex': 'm'}
#Add the second layer of objects, shallow copy and deep copy are not affected
>>> dict['new'] = {'a':1, 'b':2, 'c':5} >>> dict {'info': ['a', 'b', 100, 2], 'name': 'wang', 'age': 32, 'job': 'it', 'new': {'a': 1, 'c': 5, 'b': 2}} >>> dict_alias {'info': ['a', 'b', 100, 2], 'name': 'wang', 'age': 32, 'job': 'it', 'new': {'a': 1, 'c': 5, 'b': 2}} >>> dict_copy {'info': ['a', 'b', 100, 2], 'job': 'it', 'age': 40, 'name': 'wang', 'sex': 'm'} >>> dict_deep {'info': ['a', 'b', 1, 2], 'job': 'it', 'age': 40, 'name': 'wang', 'sex': 'm'}
2. Built-in function description:
__name__: Returns main when the main file, otherwise it returns the file name, which can be used to determine whether the main file or the import module is said to be;
__file__: The absolute path to the file;
__doc__: Comments and descriptions at the beginning of the file
example:
''' created by 2015-12-18 @author: kevin ''' if __name__ == '__main__': print('this is main file') print(__file__) print(__doc__)