Python装饰器&偏函数&异常

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值