Python装饰器&偏函数&异常
装饰器
**概念:**是一个闭包,把一个函数当做参数返回一个替代版的函数,本质上就是一个返回函数的函数
#简单装饰器
def funcl():
print("xya is cool")
def outer(func):
def inner():
print("*************")
func()
return inner
f=outer(func1)
f()
变形
def say(age):
print("xya is %d years old"%(age))
def outer(func):
def inner(age):
if age<0:
age=0
func(age)
return inner
say=outer(say)
带装饰器
def outer(func):
def inner(age):
if age<0:
age=0
func(age)
return inner
@outer #相当于say=outer(say)
def say(age):
print("xya is %d years old"%(age))
say(-10)
通用装饰器
def outer(func):
def inner(*args,**kwargs):
#添加修改内容
print("&&&&&&&&&&&&&&&")
func(*args,**kwargs)
return inner
@outer
def say(name,age):
print("my name is %s,I am %d years old"%(name,age))
#函数的参数理论上是无限制的,但是实际上最好不要超过6,7个
say("xya",10)
偏函数
import functools.partial
#偏函数
def int2(str,base=2):
return int(str,base)
print(int2("1011"))
#把一个参数固定住,形成一个新的函数
int3=functools.partial(int,base=2)