一、Python装饰器
作用:拓展原来函数功能的一种函数。
1、基本形式
定义了一个函数deco,它的参数是一个函数,然后给这个函数嵌入了计时功能。
#避免直接侵入原函数修改,但是生效需要再次执行函数
import time
def deco(func):
startTime = time.time()
func()
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
def func():
print("hello")
time.sleep(1)
print("world")
if __name__ == '__main__':
f = func
deco(f)#只有把func()或者f()作为参数执行,新加入功能才会生效
print("f.__name__ is",f.__name__)#f的name就是func
这种方法的缺点是,当需要给多个函数添加计时功能时,需要反复执行f = func; deco(f),因此使用@的方式。
#既不需要侵入,也不需要函数重复执行
import time
def deco(func):
def wrapper():
startTime = time.time()
func()
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
return wrapper
@deco
def func():
print("hello")
time.sleep(1)
print("world")
if __name__ == '__main__':
f = func #这里f被赋值为func,执行f()就是执行func()
f()
可以看到:
- deco函数就是最原始的装饰器,它的参数是一个函数,然后返回值也是一个函数。
二、带参数的装饰器
#带有不定参数的装饰器
import time
def deco(func):
def wrapper(*args, **kwargs):
startTime = time.time()
func(*args, **kwargs)
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
return wrapper
@deco
def func(a,b):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
@deco
def func2(a,b,c):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b+c))
if __name__ == '__main__':
f = func
func2(3,4,5)
f(3,4)
#func()
三、多个装饰器一起使用
def dec1(func):
print("1111")
def one():
print("2222")
func()
print("3333")
return one
def dec2(func):
print("aaaa")
def two():
print("bbbb")
func()
print("cccc")
return two
@dec1
@dec2
def test():
print("test test")
test()
输出:
aaaa
1111
2222
bbbb
test test
cccc
3333
注意到,先执行了dec2(test),然后打印aaa,接着返回了two函数(并没有执行里面的内容),two作为参数传递给dec1(two),然后打印1111。相当于执行了test=dect1(dect2(test))
,
二、plt画图
1. 图表显示问题
- 出现:Font ‘default’ does not have a glyph for ‘-’ [U+2212], substituting with a d
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 中文字体设置-黑体 ['SimHei']也可以试试
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
2. 绘图参数
常用的参数:
color:控制颜色,color=’green’
linestyle:线条风格,linestyle=’dashed’
marker:标记风格,marker = ‘o’
markerfacecolor:标记颜色,markerfacecolor = ‘blue’ 表示标记的颜色,设置none为空心
markersize:标记尺寸,markersize = ‘10’
例:
plt.plot(r, e2, marker='o', label='baseline2',markerfacecolor='none',markersize ='10')
plt.plot(r, e, marker='*', label='Proposed',markersize ='10',color='red')
更多:
linestyle:
三、保存变量pickle
#############保存########################################
import pickle
a=1
b=2
filename='d.data'
f = open(filename, 'wb')
# 将变量存储到目标文件中区
pickle.dump([a,b], f)
# 关闭文件
f.close()
#####################读取#######################
filename = 'energy.data'
f = open(filename, 'rb')
# 将文件中的变量加载到当前工作区
storedlist = pickle.load(f)
四、parser用法
五、torch学习
1.tensor
- torch的type是一个Python内置的函数,它可以返回一个对象的类型,比如torch.Tensor,torch.nn.Module等。
- torch的dtype是一个torch定义的类,它表示一个torch.Tensor中元素的数据类型,比如torch.float32,torch.int64等。
- torch.Tensor有一个type方法,它可以返回一个Tensor的数据类型,比如torch.FloatTensor,torch.LongTensor等。
LAST、常用API
- 根据概率选择随机数