# coding : utf-8
count = 0
def test():
global count
count += 1
if count != 5:
print('The count condition is not met. You need to re-execute yourself. '
'The current count is %s' %count)
return test()
else:
print('count is %s' %count)
test()
3、递归函数的说明
内存溢出
避免滥用递归
二、匿名函数lambda
1、lambda功能
定义一个轻量化的函数
即用即删除,很适合需要完成一项功能,但是此功能只在此一处使用
2、lambda定义
# coding : utf-8
f = lambda : print(1)
f()
f1 = lambda x, y=2 : x > y
print(f1(1))
users = [
{'name' : 'dewei'},
{'name' : 'xiaomu'},
{'name' : 'asan'}
]
users.sort(key=lambda x: x['name'])
print(users)
三、装饰器
1、什么是装饰器
也是一种函数
可以接受函数作为参数
可以返回函数
接收一个函数,内部对其处理,然后返回一个新函数,动态的增强函数功能
将c函数在a函数中执行,在a函数中可以选择执行或不执行c函数,也可以对c函数的结果进行二次加工处理
2、装饰器的定义
3、装饰器的用法
将被调用的函数直接作为参数传入装饰器的外围函数括弧
将装饰器与被调用函数绑定在一起
@符号+装饰器函数放在被调用函数的上一行,被调用的函数正常定义,只需要直接调用被执行函数即可
# coding : utf-8
def check_str(func):
print('func:', func)
def inner(*args, **kwargs):
print('args:', args, kwargs)
result = func(*args, **kwargs)
if result == 'ok':
return 'result is %s' % result
else:
return 'result is failed:%s' % result
return inner
@check_str
def test(data):
return data
result = test(data='no')
print(result)
result = test(data='ok')
print(result)
四、类的常用装饰器
1、classmethod
将类函数可以不经过实例化而直接被调用
# coding : utf-8
class Test(object):
def __init__(self, a):
self.a = a
def run(self):
print('run')
self.jump()
@classmethod
def jump(cls):
print('jump')
# cls.run()
t = Test('a')
t.run()
# Test.jump()