Decorator
1. Open Closed Principle
In the case of the source code does not change , add some extra features
It is open for extension, closed for modification
1.1 principle of openness: additional new features
1.2 closed principle: Do not change the source code
2 decorator
满足开放封闭原则,在不改变原函数代码及调用方式的前提下,增加新功能
# 基本装饰器
def wrapper(func):
def inner(*args): # 这里的* 是聚合
ret = func(*args) # 这里的* 是打散
return ret
return inner
@wrapper
def func1(*args):
...
Arguments decorator
## 当装饰器装饰两个以上验证方式又不相同的函数时,就用到了带参数的装饰器
def outer(choose):
def wrapper(func):
def inner(*args,**kwargs):
if choose =='func1':
print ('func1的判断条件')
ret = func()
return ret
if choose=='func2':
print ('func2的判断条件')
ret = func()
return ret
return inner
return wrapper
@outer('func1') ## 这里的 outer('func1') 先执行 返回 wrapper 函数,所以就只比标准函数多一步操作
def func1():
print('我是被装饰的函数1')
@outer('func2')
def func2():
print ('我是被装饰的函数2')
## 当然这样写很蠢;如果有操作的话可以直接对choose这个变量操作,不需要判断,因为相应的choose是不一样的
Decorative a two decorative function
def wrapper1(func):
def inner1(*args):
print ('1')
func()
print ('2')
return inner1
def wrapper2(func):
def inner2(*args):
print (3)
func()
print (4)
return inner2
@wrapper2 ## 这里的wrapper2 相当于把wrapper1也装饰了,相当于装饰
@wrapper1 ## inner1 = wrapper1(func1)
def func1(): ## inner2 = wrapper2(inner1)
print ('new king')
## 最后的结果 3,1,new king 2 4
Recursion
Recursion is not a simple calls itself , he is a kind of simplify the idea , please look at the macro issues , the details to the computer
Recursive to meet two requirements
1 recursive condition: You can continue to call itself, narrowing the scope of the problem to be solved
2 Baseline conditions: export, when the conditions are not satisfied recursion
# 阶乘问题
def jc(n):
if n==1:
return 1
else:
return n*jc(n-1)
## 斐波那契数列 第n项的值
def fbnq(n):
if n==1:
return 1
if n==0:
return 0
return fbnq(n-1)+fbnq(n-2)