python从入门到精通(DAY 2)

yipeiwu_com6年前Python基础

1、字典复制:

dict = {'name':'wang', 'sex':'m', 'age':34, 'job':'it'}

info = dict      ##别名 (二个字典指向内存的同一地址空间)

info1 = dict.copy()  #shadow copy 浅复制(嵌套字典第一层独立,第二层以下相关联)

import copy

copy.copy()      #shadow copy 浅复制

copy.deepcopy()    #deep copy  深复制(完全独立)

注:浅复制下的关联只是针对字典初始状态包含的嵌套对象,后新加的不会

例:

>>> dict
{'info': ['a', 'b', 1, 2], 'job': 'it', 'sex': 'm', 'age': 40, 'name': 'wang'}
>>> dict_alias = dict
>>> dict_copy = copy.copy(dict)
>>> dict_deep = copy.deepcopy(dict)

#添加、改变、删除第一层的对象键值,浅复制和深复制都不受影响

>>> 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'}

#改变、删除原有的第二层的对象键值,浅复制受影响,而深复制都不受影响

>>> 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'}

#添加第二层的对象,浅复制和深复制都不受影响

>>> 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、内置函数说明:

      __name__:主文件时返回main,否则返回文件名,可用来判断是否说主文件还是导入模块;

      __file__:文件的绝对路径;

      __doc__:文件开头的注释说明

例:

'''
  created by 2015-12-18
  @author: kevin
'''

if __name__ == '__main__':
  print('this is main file')
  print(__file__)
  print(__doc__)

相关文章

python中__call__方法示例分析

本文实例讲述了python中__call__方法的用法,分享给大家供大家参考。具体方法分析如下: Python中的__call__允许程序员创建可调用的对象(实例),默认情况下, __c...

Python装饰器用法实例分析

本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下: 无参数的装饰器 #coding=utf-8 def log(func): def wrapper():...

python处理按钮消息的实例详解

python处理按钮消息的实例详解

python处理按钮消息的实例详解            最新学习Python的基础知...

Django2.1.3 中间件使用详解

Django2.1.3 中间件使用详解

环境 Win10 Python3.6.6 Django2.1.3 中间件作用 中间件用于全局修改Django的输入或输出。 中间件常见用途 缓存 会话认证...

Python中使用PIL库实现图片高斯模糊实例

Python中使用PIL库实现图片高斯模糊实例

一、安装PIL PIL是Python Imaging Library简称,用于处理图片。PIL中已经有图片高斯模糊处理类,但有个bug(目前最新的1.1.7bug还存在),就是模糊半径写...