技术标签: Python
本质是函数,用来装饰其他函数,就是为其他函数添加附加功能。
import time
def timmer(func):#本质是函数,函数即“变量”
def warpper(*args,**kwargs):
start_time=time.time()
func()
stop_time=time.time()
print('the func run time is %s' %(stop_time-start_time))
return warpper
@timmer#装器饰器的引用方法
def test1():
time.sleep(3)
print('in the test1')
test1()
运行如图:
in the test1
the func run time is 3.0006024837493896
故:实现装饰器知识储备
高阶函数+嵌套函数=》装饰器
知识2-(1):
import time
def bar():
time.sleep(3)
print('in the bar')
def test1(func):
start_time=time.time()
func()
stop_time=time.time()#计算bar函数的运行时间
print("the func run time is %s "%(stop_time-start_time))
#不修改被装饰的原代码bar(),为bar添加附加功能(计时) test1即装饰器
print(bar)#bar函数门号,内存地址,也就是说加括号就是调用
test1(bar)
运行如下:
<function bar at 0x000000FD2E9AB9D8>
in the bar
the func run time is 3.000737428665161
知识2-(2):
import time
def bar():
time.sleep(3)
print('in the bar')
def test2(func):
print(func)
return func#
bar=test2(bar)
#bar内存地址,交给Test2 , 打印又返回bar内存地址,随后稪盖
bar()#运行Bar函数
运行如下:
<function bar at 0x000000FD2E9AB598>
in the bar
import time
def timer(func):
def deco():
start_time=time.time()
func()#此地址是第一次给的bar1的内存,执行的是bar1()
stop_time=time.time()
print('the func run time is %s' %(stop_time-start_time))
return deco
def bar1():
time.sleep(3)
print('in the bar')
@timer
#此句与bar1=timer(bar1)等同,想谁加上装饰器在哪加@+装饰器名
#只是这里是在bar2前,所有的bar1会成bar2
def bar2():
time.sleep(3)
print('in the bar2')
bar1=timer(bar1)
#把bar1的内存地址交给Timer,Deco函数就是“变量”,
#其接受Timer参数,故其地址就成了bar1的内存地址,并其返回赋值到了新bar1
bar1()#如此一来Bar1成了指向deco,加括号成了运行Deco()
bar2()
运行如下:
in the bar
the func run time is 3.0003163814544678
in the bar2
the func run time is 3.0003561973571777
import time
def timer(func):#A:func=bar2
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs)#B:func=bar2
stop_time=time.time()
print('the func run time is %s' %(stop_time-start_time))
return deco
def bar1():
time.sleep(3)
print('in the bar')
@timer
#bar2=timer(bar2),A,故:bar2()=deco(),当bar2()有参数,就可放到B处
#因不知道bar2有多少参数,故;用的是*args,**kwargs,用以接收不知数的参数
def bar2(name,age,sex):
time.sleep(3)
print('in the bar2:',name,age,sex)
bar1=timer(bar1)
bar1()
bar2("liang",18,"male")
运行如下:
in the bar
the func run time is 3.000230073928833
in the bar2: liang 18 male
the func run time is 3.000300645828247
网页登陆认证
Print(home()):打印home函数执行完所返回(return)的值
已往的【func(*args,**kwargs)#B:func=bar2】在源函数要求要有Return内容时,装饰器的【func(*args,**kwargs)#B:func=bar2】不加处理会导致源函数代码的Return内容丢失
故有下方:
res = func(*args, **kwargs) # from home
print("—after authenticaion ")
return res
登陆认证设本地和服务器认证。装饰器要改变升级–装饰器加上了参数
装饰器外嵌多一层函数
__author__ = "Alex Li"
import time
user,passwd = 'alex','abc123'
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":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("搞毛线ldap,不会。。。。")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local")
# home = wrapper(),因为有了参数,有括号,其与上两种有区别。它会执行
def home():
print("welcome to home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")
index()
print(home()) #wrapper()
bbs()
列表生成式
a=[]
for i in range(10):
a.append(i*2)
print (a)
运行如下:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18
在Python中,一边循环一边计算的机制,称为生成器(generator)。
b=(i*2 for i in range (10))
for i in b:
print(i)
运行如下:
0
2
4
6
8
10
12
14
16
18
a=(i*5 for i in range(10))
for i ,index in enumerate(a):
print(i,index)
print(a.__next__())#寻找并打印下一个,for一共跳2步
#取生成器下一个数据
运行如下:
0 0
5
1 10
15
2 20
25
3 30
35
4 40
45
斐波耶契数列:1,1,2,3,5,8,13,21,34,55…
def fib(max):
n,a,b=0,0,1
while n<max:
print(b)
a,b=b,a+b#a=1,b=1,n为次数
n+=1
return "done"
fib(10)
运行如下:
1
1
2
3
5
8
13
21
34
55
Out[62]:'done'
def fib(max):
n,a,b=0,0,1
while n<max:
#print(b)
yield b#想返回什么yield谁
a,b=b,a+b#a=1,b=1,n为次数
n+=1
return "done"
#此Return非函数的Return,生成器非函数,它可以不运行完而跳出来,即中断
print(fib(100))
fib_gen=fib(100)
print("-----------")
print(fib_gen.__next__())
#相当于停在yield b 那,可以出来
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
#运行结果1,1,2,3
import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
c = consumer("ChenRonghua")
c.__next__()#让其回到baozi = yield语句
b1= "韭菜馅"
c.send(b1)
#唤醒Yield并send个值给Yield,并让Yield返回该值,从而实现并行运算
b2= "猪肉馅"
c.send(b2)
运行如下:
ChenRonghua 准备吃包子啦!
包子[韭菜馅]来了,被[ChenRonghua]吃了!
包子[猪肉馅]来了,被[ChenRonghua]吃了!
import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
def producer(name):
c = consumer('A')#让其跳入生成器
c2 = consumer('B')
c.__next__()
c2.__next__()
#作用是让其都回到baozi = yield语句
print("%s开始准备做包子啦!"%name)
for i in range(5):
time.sleep(1)
print("做了1个包子,分两半!")
c.send(i)
c2.send(i)
producer("alex")
运行结果:
A 准备吃包子啦!
B 准备吃包子啦!
alex开始准备做包子啦!
做了1个包子,分两半!
包子[0]来了,被[A]吃了!
包子[0]来了,被[B]吃了!
做了1个包子,分两半!
包子[1]来了,被[A]吃了!
包子[1]来了,被[B]吃了!
做了1个包子,分两半!
包子[2]来了,被[A]吃了!
包子[2]来了,被[B]吃了!
做了1个包子,分两半!
包子[3]来了,被[A]吃了!
包子[3]来了,被[B]吃了!
做了1个包子,分两半!
包子[4]来了,被[A]吃了!
包子[4]来了,被[B]吃了!
可以直接作用于for循环的数据类型有:
from collections import Iterable#导入
print (isinstance('abc',Iterable))#abc为判断对象
print (isinstance({
},Iterable))
print (isinstance([],Iterable))
运行如下:
True
True
True
找出一个对象的所有可用操作:
a={
}
dir(a)#a为对象
运行如下:
['__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'clear',
'copy',
'fromkeys',
'get',
'items',
'keys',
'pop',
'popitem',
'setdefault',
'update',
'values']
生成器都是Iterator对象,但List,Dict,Str虽然是Itearable,却不是Iterator
把List,Dict,Str等Iterable变成Itearator的方法是使用iter()函数
a=[1,2,3]
from collections import Iterator#导入
from collections import Iterable#导入
print (isinstance(a,Iterator))#判断对象是否为迭代器
b=iter(a)
print (isinstance(b,Iterator))#abc为判断对象
运行结果:
False
True
Iterator可以用以下代码抓取Iterator错误从而不使__next()__超范围报错
it=iter([1,2,3,4])
while True:
try :
x=next(a)
except StopIteration:
break#遇StopIteration退出来
所有的for ,in …:都是迭代器方法
Pythoon自己本身带有的函数
更多详情,菜鸟教程
print (all([0,1,15,-5]))#0为False
print (all([3,1,15,-5]))
运行如下:
False
True
print (any([0,1,15,-5]))#0为False
print(any([]))
运行如下:
True
False
a=ascii(["a",1,"我是谁"])
print(type(a),[a])
运行如下:
<class 'str'> ["['a', 1, '\\u6211\\u662f\\u8c01']"]
#注意双引号
print(bin(2000))
运行如下:
0b11111010000#b是代表二进
print(bool([]))
print(bool([1,3]))
运行如图
False
True
a=bytes("adcde",encoding="utf-8")
print('a')
print(a.capitalize(),a)
#字符串,二进字节,不可以直接更改,要应用,要放到另一个新的变量名
b=bytearray("abcde",encoding="utf-8")
print(b[1])#把b的Ascii码打印出来
b[1]=101#把e放入到字节数组中,不可以直接b[1]=e,要赋值Ascii码
print (b)
运行如图
a
b'Adcde' b'adcde'#b是字节
98
bytearray(b'aecde')
print(callable({
}))#集合不可调用
def sa():
pass
print(callable(sa))#凡是可加括号都可调用
运行如下:
False
True
print(chr(98))
print(ord("a"))
#结果是b,97
classmethod() 类方法
compile底层字符串转源代码
code="for i in range(10):print(i)"
print(code)
c=compile(code,'',"exec")#exec把字符串转码
print(c)
exec(c)#执行C
运行如下:
for i in range(10):print(i)
<code object <module> at 0x0000002DEE2750C0, file "", line 1>
0
1
2
3
4
5
6
7
8
9
print(divmod(9,2))
运行如下:
calc= lambda n:print(n)
#只可执行简单语句,for都不行,只能3圆运算,如
'''
calc= lambda n:3 if n<4 else n
#如果n<4,选3,否则是n
print(calc(2))#将打印3
print(calc(7))#将打印7
'''
calc(5)
运行如下:
res=filter(lambda n:n>5 ,range(10))
res1=map(lambda n:n*2,range(10))
import functools
#map(Function,Iterable),把迭代对像按function进行操作
res3=functools.reduce(lambda x,y:x*y,range(1,10))
#reduce() 函数会对参数序列中元素进行累积,x初值0,y为1,1加到10
for i in res:
print(i,"res1")
for i in res1:
print(i,"res1")
print(res3)
运行结果如下:
6 res1
7 res1
8 res1
9 res1
0 res1
2 res1
4 res1
6 res1
8 res1
10 res1
12 res1
14 res1
16 res1
18 res1
362880
a=frozenset(set([1,2,3,4]))
#a.add("a")#会出错
print(a)
print(hash("liang"))#liang哈希值
运行如下:
hex(9999)
运行如下:
print(round(1.234567,3))
运行如下:
a={
6:2,8:2,-5:6,99:6,88:99}
print(a)
print(sorted(a.items()))#按Key排
print(sorted(a.items(),key = lambda x: x[1]))
#按vaule排,x[1]为vaules,x[0]为key
运行如下:
{
6: 2, 8: 2, -5: 6, 99: 6, 88: 99}
[(-5, 6), (6, 2), (8, 2), (88, 99), (99, 6)]
[(6, 2), (8, 2), (-5, 6), (99, 6), (88, 99)]
a=[1,2,3,4]
b=["a","b","c","d"]
c=zip(a,b)
for i in c:
print(i)
运行如下:
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
序列化:把内容从内存存到硬盘,反序列化与之相反
f=open("序列化1.txt","w")
info={
"name":"liang",
"age":18,
"sex":"male"
}
f.write(str(info))
f.close()
f=open("序列化1.txt","r")
data=eval(f.read())
print(data["sex"])
运行如下:
此种方法代码相对繁多,功能少,故有标准的序列化:
import json
f=open("序列化2.txt","w")
info={
"name":"liang",
"age":18,
"sex":"male"
}
f.write(json.dumps(info))#序列化
f.close()
f=open("序列化2.txt","r")
data=json.loads(f.read())#反序列化
print(data["sex"])
运行如下:
Json正在替换Xml这种信息交换文件,Java也认识此文件
pickle与Json是一样的,但Pickle是二进㓡文件 ,要用wb,rb,且Pickle只有在本Python语言可用
Pickle:
import pickle
f=open("序列化3.txt","wb")
info={
"name":"liang",
"age":18,
"sex":"male"
}
pickle.dump(info,f)#等同f.write(json.dumps(info))#序列化
f.close()
f=open("序列化3.txt","rb")
data=pickle.load(f)#等同data=json.loads(f.read())#反序列化
print(data["sex"])
运行结果:
项目名
k9/
|-- bin 存放脚本,执行文件等
| |-- k9 项目名
|
|-- k9/
| |-- tests /测试代码
| | |-- __init__.py
| | |-- test_main.py 测试代码
| |
| |-- __init__.py
| |-- main.py 主程序
|
|-- docs 文档和配置
| |-- conf.py 配置文件
| |-- abc.rst
|
|-- setup.py 安装,部署,脚本打包
|-- requirements.txt 存放依赖的外部Python包列表
|-- README 项目说明文档
引自科子–linux运维之路
绝对目录:
import os
print(os.path.abspath(".")) #当前目录的绝对路径
print(os.path.abspath(r"..")) #上级目录的绝对路径
print(os.path.dirname(os.path.abspath(".")))
#找到不要当前文件名的路径,即也是文件上级目录的绝对路径
print(os.path.dirname(os.path.dirname(os.path.abspath("."))))
#比原来再退一级
运行如下;
相对目录(编软件用):加入到系统中
import os ,sys
Base_path=os.path.dirname(os.path.abspath("."))
sys.path.append(Base_path)
from conf import settings#不同目录间进行模块调用
from core import main
main.loggin()
路径文件如下:
Settings.py无代码
main.py如图:
运行如下:
_allow_resetlogs_corruption 今天我将生产中的10g oracle数据库的冷备份文件,在11g测试环境进行了还原恢复,但..._allow_resetlogs_corruption
using System.Collections;using System.Collections.Generic;using UnityEngine;using XLua;public class MyHelloWord : MonoBehaviour{ private LuaEnv luaEnv; void Start() { luaE..._lua中调用unityengine
以下为linux常用的命令举例。(注:#后面的为注释,输入命令时不要写)(四)文件管理4.1 cat(把文件传到基本输出)cat file.txt #显示文件file.txt的内容cat -n file.txt #显示文件file.txt的内容,由1开始对所有输出的行数编号cat -b file.txt #显示文件file.txt的内容,由1开始对所有输出的行数编号,不..._mv abc.txt 333.txt
jdk jar包 引包引多了 HTTP Status 500 - java.lang.ClassNotFoundException: org.apache.jsp.register_jsp 去掉<!---->的注释 ...
需求说明: 今天在调试服务器的时候,需要创建用户的随机密码,想了下,在linux环境中是否能够生成呢,就搜索了下,然后结合看到的帖子,分析一个可以生成密码的命令,在此记录下:操作过程:通过/dev/urandom工具生成随机密码# cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 32;echoBLgH6WT6nVrhiPWekQDVXdvwORPFoXJA# cat /dev/urandom | tr -dc a-zA-Z0-9#@ | head -
目录说明/etc/asteriskAsterisk主目录,包含其它关于Asterisk的配置文件; *zaptel.conf这个配置文件放在/etc,因为其它软件也可以使用Zaptel这个硬件及其驱动,所以不是放在/etc/asterisk里./usr/lib/asterisk/modules这个目录包含所有可以加载Asterisk
el-upload单文件上传,单选文件 覆盖已有文件_el-upload on-exceed
通过python操作word、pdf_python获取pdf页数
1,引入相关包 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> ..._springboot + sentinel +apollo
交叉编辑工具获取网址:https://sourcery.mentor.com/sgpp/lite/arm/portal/subscription?@template=lite 需要说明的是,codesourcery 公司提供的免费编译器是最核心最基本的功能,有时我们移植其他开源软件,还需要其他的依赖库,比如 png,zlib, jpeg 等,其实这些也是比较常用的库
selenium用于自动测试场景比较多,但是由于它本身就是基于浏览器操作模拟的,所以可以用来获取网页数据,这里的数据就不是海量的泛爬取了,而是有目的,有周期的重复爬取。安装安装的主要问题就是webdriver的版本号问题,需要完全一致,我就是没有注意自己Chrome已经升级了一个小版本,结果运行不起来。webdriver.exe路径加入系统path的问题,有试过通过代码webdriver.C..._selenium 不重复登录
iOS 13 如期而至,虽然正式版还没出来,但是适配工作可以开展起来啦。在适配 iOS 13 过程中,遇到了如下一些问题。1. UITextField 的私有属性 _placeholderLabel 被禁止访问了遇到的第一个崩溃是修改UITextField的placeholder的颜色,..._ios {length =, bytes = 0x }