加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python的装饰器功能实例

发布时间:2020-12-17 07:17:58 所属栏目:Python 来源:网络整理
导读:感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。 Python中的装饰器本质上是一个高阶函数,它接收一个函数,并且对这个函数进行包装,从而改变原函数的默认行为。 # 来自jb51.cc@deco1(deco_arg)@deco2def func(): pass 相当于 # 来自jb51.ccfu
感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编来看看吧。
Python中的装饰器本质上是一个高阶函数,它接收一个函数,并且对这个函数进行包装,从而改变原函数的默认行为。

# 来自52php.cn
@deco1(deco_arg)
@deco2
def func(): pass
相当于

# 来自52php.cn
func = deco1(deco_arg)(deco2(func))
Demo如下:

# 来自52php.cn
# -*-coding:utf-8 -*-
def decorator(str):
  print str
  def retfn(fn):
    def retfn(*arg):
      print '已装饰' # 装饰
      return fn(*arg) # 调用原始函数
    return retfn
  return retfn
 
@decorator("实例化装饰器")
def test(str0,str1):
  print str0,str1
 
test('Hello','world');

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读