第一个程序
匿名函数-anonymousfunction
# encoding: utf-8
'''
# @Author : ccq
# @File : anonymousfunction.py
# @Time : 2019/6/10 15:27
'''
# 匿名函数
calculate = lambda x: x * 3
print(calculate(2))
第二个程序
装饰器-decorator
# encoding: utf-8
'''
# @Author : ccq
# @File : decorator.py
# @Time : 2019/6/10 14:17
'''
# 装饰器
# 装饰器本质是函数
import time
def timmer(func):
def warpper(*args, **kwargs):
start_time = time.time()
func(*args,**kwargs)
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()
#上面就是写一个装饰器的例子。
#函数和变量是类似的。例子如下:
# encoding: utf-8
'''
# @Author : ccq
# @File : variableandfunction.py
# @Time : 2019/6/10 16:05
'''
# 函数和变量
def function(x):
print(x)
f = function
f(2)
#首先定义了一个名字为function的函数,如果把f=function和f(2)去掉,改成function(2),这个程序一样执行,这就是函数。但是,我在这里把function这个变量名赋值给f(即f=function),那么实际上f就是function,只是这个函数多了个小名,不论使用function(2)这样的代码,还是f(2),最终都是调用这个函数。
#理解了这个我们来看下面的代码
import time
def knowtime():
print("I want to know the time!")
time.sleep(2)
def runtime(func):
start_time = time.time()
func()
stop_time = time.time()
print("the time is %s" % (stop_time - start_time))
runtime(knowtime)
#这个看起来是一个简单的装饰器。knowtime没有被添加任何代码,而最后整个程序显示了程序开始到程序结束的时间差。
#但是不符合一个原则,就是它改变了调用方式。和最上面的那段代码对比会发现,原来的方法应该是knowtime()。然而,现在却变成了runtime(knowtime)。这改变了调用方式。所以它并不是一个装饰器。
#它就是一个高阶函数的使用,把konwtime这个函数名作为实参传递到runtime函数中使用。最后达到了装饰器的效果。
#再来看下面这段代码。
import time
def bar():
time.sleep(0.3)
print("in the bar")
def test2(func):
print(func)
return func
bar = test2(bar)
bar()
#上面的这段代码就在没有修改调用方式的情况下进行了功能添加。
#PS:函数嵌套的定义是在一个函数的函数体内使用def再去申明一个新的函数。就像下面这样:
def foo():
print("in foo")
def bar():
print("in bar")
bar()
foo()
#装饰器《=高阶函数+嵌套函数,因此
import time
def test1():
time.sleep(2)
print("in test1")
def test2():
time.sleep(2)
print("in test2")
def timer(func):
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the time is %s" % (stop_time - start_time))
return deco
test1 = timer(test1)
test2 = timer(test2)
test1()
test2()
#简单的装饰器就完成了!
#上面这段代码和最开头的代码一对比就发现,@timer 这个用法可以代替test1=timer(test1)。
#使用的时候需要注意:@timer放在test1定义之前,但是timer函数的定义也要放在test1函数定义之前。
#但是如果出现一个方法不需要参数,另外的方法需要一个或者多个参数,上面的代码就行不通了。那么就需要改进
import time
def timer(func):
def deco(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
stop_time = time.time()
print("the time is %s" % (stop_time - start_time))
return deco
@timer
def test1():
time.sleep(2)
print("in test1")
@timer
def test2(name, age):
time.sleep(1)
print("in test2", name, age)
test1()
test2("ccq", 20)
#通过比较可以看到,区别在deco和func多了2个参数*args,**kwargs。加上这两个参数,这个装饰器就变成通用的了。
#PS:*args可以接收多个位置参数,**kwargs可以接收多个关键字参数。