闭包

  1. def make_arerage():
  2. l1 = []
  3. def average(price):
  4. l1.append(price)
  5. total = sum(l1)
  6. return total/len(l1)
  7. return average
  8. avg = make_everage()
  9. print(avg(100000))
  10. print(avg(110000))

闭包的作用:

  1. # 闭包就是嵌套函数存在的,存在嵌套函数之中的,而且是内层函数对外层非全局变量的引用,会产生闭包。引用的变量也叫自由变量,不会随着函数的结束而消失,会一直保存在内存中,最终的目的是保证了数据的安全

装饰器

  1. import time
  2. user = 'alex'
  3. passwd = 'abc13'
  4. def auth(auth_type):
  5. print("auth func:",auth_type)
  6. def outer_wrapper(func):
  7. def wrapper(*args, **kwargs):
  8. print("wrapper func args:",*args, **kwargs)
  9. if auth_type == "local":
  10. usernmae = input("用户名>>>>>")
  11. password = input("密码>>>>>>")
  12. if user == usernmae and passwd == password:
  13. print("\033[32;1mUser\033[0m")
  14. return func(*args, **kwargs)
  15. else:
  16. exit("\033[31;1m错误\033[0m")
  17. elif auth_type == "ldap":
  18. print("搞毛线ldap,不会。。。")
  19. return wrapper
  20. return outer_wrapper
  21. def index():
  22. print("in index")
  23. @auth(auth_type = "local")
  24. def home(name):
  25. print("in home",name)
  26. return "from home"
  27. @auth(auth_type = 'ldap')
  28. def bbs():
  29. print("in bbs")
  30. print(home('alex'))
  31. index()
  32. bbs()

random模块

  1. import random
  2. random.random()
  3. random.randint(1,3) # 1-3的整数包括3
  4. import random
  5. print(random.random())
  6. print(random.randint(1,20))
  7. print(random.randrange(1,3)) # 顾头不顾尾,不包含3
  8. print(random.choice('12345')) # 可迭代对象中随机取一个
  9. print(random.sample('12345',2)) # 可迭代对象中随机取两个
  10. print(random.uniform(1,10)) # 1-10的浮点数
  11. items = [1,2,3,4,5,6,7]
  12. random.shuffle(items) #洗牌 打乱items的顺序
  13. print(items)
  1. import random
  2. checkcode = ''
  3. for i in range(4):
  4. checkcode += str(random.randrange(10))
  5. print(checkcode)

os模块

  1. import os
  2. os.getcwd() 获取当前工作目录
  3. os.chdir("C\\Users") 改变当前脚本工作
  4. os.curdir 返回当前目录:('.')
  5. os.pardir 获取当前目录的父目录:('..')
  6. os.makedirs(r"c:\a\b\c\d") 可生成多层递归目录
  7. os.removedirs(r"c:\a\b\c\d") 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,以此类推
  8. os.mkdir(r"dirname") 生成单级目录
  9. os.rmdir(r'dirname') 删除单级目录
  10. os.listdir(r'dirname') 查看当前的目录 包括隐藏文件,并以列表方式打印
  11. os.remove() 删除一个文件
  12. os.rename('oldname','newname') 重命名文件/目录
  13. os.stat('path/filename') 获取文件/目录信息
  14. os.sep 输出操作系统特定的路径分隔符,win下位“\\”,Linux下为“/”
  15. os.linesep 输出当前当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
  16. os.pathsep 输出用于分割文件路径的字符串
  17. os.name 输出字符串指示当前使用平台。win->'nt';linux->'posix'
  18. os.system("bash command") 运行shell命令,直接显示
  19. os.environ 获取系统环境变量
  20. os.path.abspath(path) 返回path规范化的绝对路径
  21. os.path.split(path) path分割成目录和文件名用元组返回
  22. os.path.dirname() 返回path的目录,其实就是os.path.split(path)的第一个元素
  23. os.path.basename(path) 返回path最后的文件名。如果path以/或\结尾,那么就会返回空值。
  24. os.path.exists(path) 如果path存在,返回True,不存在返回False
  25. os.path.isabs(path) 如果path是绝对路径,返回True
  26. os.path.isfile(path) 如果path是一个存在的文件,则返回True,否则返回False
  27. os.path.isdir(path) 如果path是一个存在的目录,则返回True,否则返回False
  28. os.path.join(path1[,path2[,...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
  29. os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
  30. os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间

sys模块

  1. sys.argv 命令行参数List,第一个元素是程序本身路径
  2. sys.exit(n) 退出程序,正常退出时exit(0)
  3. sys.version 获取python解释程序的版本信息
  4. sys.maxint 最大的Int
  5. sys.path 返回模块的搜索路径,初始化时使用python环境变量的值
  6. sys.platform 返回操作系统平台名称
  7. sys.stdout.write('please:')
  8. val = sys.stdin.readline()[:-1]

shutil模块

  1. shutil.copyfile('userinfo1.txt','test1') # 复制文件到另一个文件
  2. shutil.copymode(src,dst) 仅拷贝权限、内容、组、用户均不变
  3. shutil.copysta(src,dst) 拷贝状态的信息,包括:mode bits,atime,mtime,flags
  4. shutil.copy(src,dst) 拷贝文件和权限
  5. shutil.copy2(src,dst) 拷贝文件和状态信息
  6. shutil.ignore_patterns(*patterns)
  7. shutil.copytree(src,dst,symlinks=False,ignore=None) 递归的去拷贝文件
  8. shutil.retree(path[,ignore_errors[,onerror]]) 递归的去删除文件
  9. shutil.move(src,dst) 递归的去移动文件
  10. shutil.make_archive('shutil_archive_test','zip','path(路径)') 把后边的文件夹压缩到shutil_archive_test.zip
  11. shutil对压缩包的处理是调用ZipFileTarFile两个模块来进行的
  12. import zipfile
  13. # 压缩
  14. z = zipfile.ZipFile('laxi.zip','w')
  15. z.write('a.log')
  16. z.write('data.data')
  17. z.close()
  18. # 解压
  19. z = zipfile.ZipFile('laxi.zip','r')
  20. z.extractall()
  21. z.close()
  22. import tarfile
  23. # 压缩
  24. tar = trafile.open("your.tar",'w')
  25. tar.add('/Users/xxx/bbs.zip', arcname='bbs.zip')
  26. tar.add('/Users/xxx/cmdb.zip', arcname='cmdb.zip')
  27. tar.close()
  28. # 解压
  29. tar = tarfile.open('your.tar','r')
  30. tar.extractall() # 可设置解压地址
  31. tar.close()

shelve模块

  1. # shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
  2. import shelve
  3. import datetime
  4. d = shelve.open('shelve_test') # 打开一个文件
  5. # class Test(object):
  6. # def __init__(self,n):
  7. # self.n = n
  8. # t = Test(123)
  9. # t2 = Test(123443)
  10. # info = {'age':18,'username':"sfs"} # 写进去
  11. #
  12. # name = ['alex','wuasi','twusi']
  13. # d['name'] = name # 吃酒列表
  14. # d['info'] = info # 持久dict
  15. # d['date'] = datetime.datetime.now()
  16. # 读出来
  17. print(d.get("name"))
  18. print(d.get("info"))
  19. print(d.get("date"))
  20. d.close()

python读取xml,修改xml

  1. https://www.cnblogs.com/alex3714/articles/5161349.html

ConfigParser 模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser

  1. [DEFAULT]
  2. serveraliveinterval = 45
  3. compression = yes
  4. compressionlevel = 9
  5. forwardx11 = yes
  6. [bitbucket.org]
  7. user = hg
  8. forwardx11 = yes
  9. [topsecret.server.com]
  10. host port = 50022
  11. forwardx11 = no
  1. # 写入
  2. import configparser
  3. config = configparser.ConfigParser()
  4. config["DEFAULT"] = {'ServerAliveInterval': '45',
  5. 'Compression': 'yes',
  6. 'CompressionLevel': '9'}
  7. config['bitbucket.org'] = {}
  8. config['bitbucket.org']['User'] = 'hg'
  9. config['topsecret.server.com'] = {}
  10. topsecret = config['topsecret.server.com']
  11. topsecret['Host Port'] = '50022' # mutates the parser
  12. topsecret['ForwardX11'] = 'no' # same here
  13. config['DEFAULT']['ForwardX11'] = 'yes'
  14. config['bitbucket.org']['ForwardX11'] = 'yes'
  15. with open('ha.conf', 'w') as configfile:
  16. config.write(configfile)
  1. # 读
  2. import configparser
  3. conf = configparser.ConfigParser()
  4. conf.read('ha.conf')
  5. print(conf.defaults())
  6. print(conf.sections())
  7. print(conf['bitbucket.org']['user'])

hashlib模块

  1. # 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法
  2. # 如果是中文的话,需要encode成utf-8编码
  3. import hmac
  4. h = hmac.new('字体'.encode('utf-8'))
  5. print(h.hexdigest())
  6. import hmac
  7. h = hmac.new(b'hello'.encode('utf-8'))
  8. print(h.hexdigest())
  9. import hashlib
  10. m = hashlib.md5()
  11. m.update(b"sdf")
  12. print(m.hexdigest())
  13. m.update(b"It's me")
  14. print(m.hexdigest())
  15. m.update(b"It's been a func")
  16. print(m.hexdigest())
  17. m2 = hashlib.md5()
  18. m2.update(b"HelloIt's me")
  19. print(m2.hexdigest())
  20. m3 = hashlib.sha1()
  21. m3.update(b"password")
  22. print(m3.hexdigest())

python 闭包,装饰器,random,os,sys,shutil,shelve,ConfigParser,hashlib模块的更多相关文章

  1. Python常用模块(logging&re&时间&random&os&sys&shutil&序列化&configparser&&hashlib)

    一. logging(日志模块) 二 .re模块 三. 时间模块 四. random模块 五. os模块 六. sys模块 七. shutil模块 八. 序列化模块(json&pickle&a ...

  2. 模块、包及常用模块(time/random/os/sys/shutil)

    一.模块 模块的本质就是一个.py 文件. 导入和调用模块: import module from module import xx from module.xx.xx import xx as re ...

  3. Python闭包装饰器笔记

    Python三大器有迭代器,生成器,装饰器,这三个中使用最多,最重要的就是装饰器.本篇将重要从函数嵌套开始讲起,从而引入闭包,装饰器的各种用法等. python中的一切都是一个对象(函数也是) 1.首 ...

  4. python 闭包@装饰器

    1.装饰器 装饰器(Decorator)相对简单,咱们先介绍它:“装饰器的功能是将被装饰的函数当作参数传递给与装饰器对应的函数(名称相同的函数),并返回包装后的被装饰的函数”,听起来有点绕,没关系,直 ...

  5. python闭包&装饰器&偏函数

    什么是闭包? 首先还得从基本概念说起,什么是闭包呢?来看下维基上的解释: 在计算机科学中,闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数.这个被引用的 ...

  6. python 闭包&装饰器(一)

    一.闭包 1.举例 def outer(): x = 10 def inner(): # 内部函数 print(x) # 外部函数的一个变量 return inner # 调用inner()函数的方法 ...

  7. 【Python】 闭包&装饰器

    python中的函数本身就是对象,所以可以作为参数拿来传递.同时其允许函数的层级嵌套定义,使得灵活性大大增加. 闭包 闭包的定义:将函数的语句块与其运行所需要的环境打包到一起,得到的就是闭包对象.比如 ...

  8. python 常用模块之random,os,sys 模块

    python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...

  9. python笔记-1(import导入、time/datetime/random/os/sys模块)

    python笔记-6(import导入.time/datetime/random/os/sys模块)   一.了解模块导入的基本知识 此部分此处不展开细说import导入,仅写几个点目前的认知即可.其 ...

  10. Python 进阶_闭包 & 装饰器

    目录 目录 闭包 函数的实质和属性 闭包有什么好处 小结 装饰器 更加深入的看看装饰器的执行过程 带参数的装饰器 装饰器的叠加 小结 装饰器能解决什么问题 小结 闭包 Closure: 如果内层函数引 ...

随机推荐

  1. 数字IC前后端设计中的时序收敛(三)--Hold违反的修复方法

    本文转自:自己的微信公众号<数字集成电路设计及EDA教程>(二维码见博文底部) 里面主要讲解数字IC前端.后端.DFT.低功耗设计以及验证等相关知识,并且讲解了其中用到的各种EDA工具的教 ...

  2. U盘被写保护大全解

    相信大家的U盘在使用的过程中多或少都有出现过一些问题,写保护,程序写蹦而造成的逻辑错误,或者在使用过程中因电脑而中毒,内部零件损伤等等各种各样倒霉的错误. 简单了解一下是个什么东西吧.U盘写保护其实就 ...

  3. Spring Boot 2.0 迁移指南

    ![img](https://mmbiz.qpic.cn/mmbiz_jpg/1flHOHZw6Rs7yEJ6ItV43JZMS7AJWoMSZtxicnG0iaE0AvpUHI8oM7lxz1rRs ...

  4. I/O:ByteBuffer

    ByteBuffer: static ByteBuffer allocate(int capacity) :分配一个新的字节缓冲区. static ByteBuffer allocateDirect( ...

  5. 性能测试-实例讲解VU、RPS、RT公式换算

    概述 今天看到一篇文章讲解VU.RPS.RT,中间有一个公式如下图 并发数 = RPS * 响应时间  于是我在本地做了几次实验,试图验证一下公式的准确性 实验网站 www.baidu.com 第一次 ...

  6. Jquery UI sortable

    所有的事件回调函数都有两个参数:event和ui,浏览器自有event对象,和经过封装的ui对象 ui.helper - 表示sortable元素的JQuery对象,通常是当前元素的克隆对象 ui.p ...

  7. Excel催化剂开源第26波-Excel离线生成二维码条形码

    在中国特有环境下,二维码.条形码的使用场景非常广泛,因Excel本身就是一个非常不错的报表生成环境,若Excel上能够直接生成二维码.条形码,且是批量化操作的,直接一条龙从数据到报表都由Excel完成 ...

  8. bootstrap table 父子表实现【无限级】菜单管理功能

    bootstrap table 父子表实现[无限级]菜单管理功能 实现效果 前端代码 <%@ page language="java" import="java.u ...

  9. Golang高效实践之interface、reflection、json实践

    前言 反射是程序校验自己数据结构和类型的一种机制.文章尝试解释Golang的反射机制工作原理,每种编程语言的反射模型都是不同的,有很多语言甚至都不支持反射. Interface 在将反射之前需要先介绍 ...

  10. (技能篇)双机热备之Oracle切换故障处理

    背景: 以前做的的一个项目中使用了某国产双机热备产品,但是在数据库做双机热备时出现了一些问题,没办法.不得不研究一番了!经过两天的研究终于问题得以解决.将问题处理步骤记录下来以备后用,也希望能帮助到需 ...