闭包

def make_arerage():
l1 = []
def average(price):
l1.append(price)
total = sum(l1)
return total/len(l1)
return average
avg = make_everage()
print(avg(100000))
print(avg(110000))

闭包的作用:

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

装饰器

import time
user = 'alex'
passwd = 'abc13' def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args:",*args, **kwargs)
if auth_type == "local":
usernmae = input("用户名>>>>>")
password = input("密码>>>>>>")
if user == usernmae and passwd == password:
print("\033[32;1mUser\033[0m")
return func(*args, **kwargs)
else:
exit("\033[31;1m错误\033[0m")
elif auth_type == "ldap":
print("搞毛线ldap,不会。。。") return wrapper
return outer_wrapper def index():
print("in index") @auth(auth_type = "local")
def home(name):
print("in home",name)
return "from home" @auth(auth_type = 'ldap')
def bbs():
print("in bbs") print(home('alex'))
index()
bbs()

random模块

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

os模块

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

sys模块

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

shutil模块

shutil.copyfile('userinfo1.txt','test1') # 复制文件到另一个文件
shutil.copymode(src,dst) 仅拷贝权限、内容、组、用户均不变
shutil.copysta(src,dst) 拷贝状态的信息,包括:mode bits,atime,mtime,flags
shutil.copy(src,dst) 拷贝文件和权限
shutil.copy2(src,dst) 拷贝文件和状态信息
shutil.ignore_patterns(*patterns)
shutil.copytree(src,dst,symlinks=False,ignore=None) 递归的去拷贝文件
shutil.retree(path[,ignore_errors[,onerror]]) 递归的去删除文件
shutil.move(src,dst) 递归的去移动文件
shutil.make_archive('shutil_archive_test','zip','path(路径)') 把后边的文件夹压缩到shutil_archive_test.zip中
shutil对压缩包的处理是调用ZipFile和TarFile两个模块来进行的
import zipfile
# 压缩
z = zipfile.ZipFile('laxi.zip','w')
z.write('a.log')
z.write('data.data')
z.close() # 解压
z = zipfile.ZipFile('laxi.zip','r')
z.extractall()
z.close() import tarfile # 压缩
tar = trafile.open("your.tar",'w')
tar.add('/Users/xxx/bbs.zip', arcname='bbs.zip')
tar.add('/Users/xxx/cmdb.zip', arcname='cmdb.zip')
tar.close() # 解压
tar = tarfile.open('your.tar','r')
tar.extractall() # 可设置解压地址
tar.close()

shelve模块

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

python读取xml,修改xml

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

ConfigParser 模块

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

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

hashlib模块

# 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法
# 如果是中文的话,需要encode成utf-8编码
import hmac
h = hmac.new('字体'.encode('utf-8'))
print(h.hexdigest())
import hmac
h = hmac.new(b'hello'.encode('utf-8'))
print(h.hexdigest()) import hashlib
m = hashlib.md5()
m.update(b"sdf")
print(m.hexdigest())
m.update(b"It's me")
print(m.hexdigest())
m.update(b"It's been a func")
print(m.hexdigest())
m2 = hashlib.md5()
m2.update(b"HelloIt's me")
print(m2.hexdigest())
m3 = hashlib.sha1()
m3.update(b"password")
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. Oracle数据库---触发器

    SQL> --当我们对empnew执行删除操作之后,它就会出现一个提示信息,提示:这是删除操作!SQL> CREATE TRIGGER first_trigger 2 AFTER DELE ...

  2. java字符串的替换replace、replaceAll、replaceFirst的区别

    看代码: String s = "my.test.txt"; System.out.println(s.replace(".", "#")) ...

  3. 自定义ApplicationContextInitializer接口实现

    简介 ApplicationContextInitializer是Spring框架提供的接口, 该接口的主要功能就是在接口ConfigurableApplicationContext刷新之前,允许用户 ...

  4. 个人永久性免费-Excel催化剂功能第102波-批量上传本地图片至网络图床(外网可访问)

    自我突破,在100+功能后,再做有质量的功能,非常不易,相对录制视频这些轻松活,还是按捺不住去写代码,此功能虽小,但功课也做了不少,希望对真正有需要的群体带来一些惊喜. 背景介绍 图床的使用,一般是写 ...

  5. Codeforces 1144 E. Median String

    原题链接:https://codeforces.com/problemset/problem/1144/E tag:字符串模拟,大整数. 题意:给定两个字符串,求字典序中间串. 思路:可以把这个题当做 ...

  6. Cesium 学习(三)各种资源链接

    1.前言 前面已经介绍如何获得以及安装部署Cesium,接下来分享下学习资源链接,其中访问最多的是官网以及超图.火星的demo网站. 2.官网地址及介绍 官网:https://cesiumjs.org ...

  7. PHP--仿微信, 通过登陆者用户名显示好友列表,显示头像和昵称

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. mount命令中offset参数的意义

    mount命令中offset参数的意义        感觉好久没有来写东西了,最近一直忙个不停,今天也一样,总感觉时间不够用,唉,这里来临时总结一下工作中的一点小收获吧.今天要说的是我们常用的解压IM ...

  9. python中的内存机制

    首先要明白对象和引用的概念 (例子:a=1, a为引用,1为对象,对象1的引用计数器为1,b=1此时内存中只有一个对象1,a,b都为引用,对象的引用计数器此时为2,因为有两个引用) a=1,b=1 i ...

  10. sqlserver清除日志

    在一次处理数据库日志已满的过程中,发现有的时候数据库日志不能清除,经实验,可以通过以下方式来完成. 使用exec sp_cycle_errorlog 来清除sql系统本身的临时日志. dump tra ...