欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python裝飾器模式定義與用法分析

 更新時(shí)間:2018年08月06日 12:11:26   作者:初行  
這篇文章主要介紹了Python裝飾器模式定義與用法,結(jié)合實(shí)例形式分析了Python裝飾器模式的具體定義、使用方法及相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python裝飾器模式定義與用法。分享給大家供大家參考,具體如下:

裝飾器模式定義:動(dòng)態(tài)地給一個(gè)對(duì)象添加一些額外的職責(zé)。

在Python中Decorator mode可以按照像其它編程語言如C++, Java等的樣子來實(shí)現(xiàn),但是Python在應(yīng)用裝飾概念方面的能力上遠(yuǎn)不止于此,Python提供了一個(gè)語法和一個(gè)編程特性來加強(qiáng)這方面的功能。

首先需要了解一下Python中閉包的概念:如果在一個(gè)內(nèi)部函數(shù)里,對(duì)在外部作用域(但不是在全局作用域)的變量進(jìn)行引用,那么內(nèi)部函數(shù)就被認(rèn)為是閉包(closure)。

def makeblod(fn):
  def wrapped():
    return '<b>'+fn()+'</b>'
  return wrapped
def makeitalic(fn):
  def wrapped():
    return '<i>'+fn()+'</i>'
  return wrapped
@makeblod
@makeitalic
def hello():
  return 'hello world'
print hello()

運(yùn)行結(jié)果:

<b><i>hello world</i></b>

def deco(arg):
  def _deco(func):
    def __deco():
      print "before %s called [%s]." % (func.__name__, arg)
      func()
      print "after %s called [%s]." % (func.__name__, arg)
    return __deco
  return _deco
@deco("mymodule")
def myfunc():
  print "myfunc() called."
myfunc()

運(yùn)行結(jié)果:

before myfunc called [mymodule].
myfunc() called.
after myfunc called [mymodule].

關(guān)于閉包學(xué)習(xí)可參考:http://www.dbjr.com.cn/article/54498.htm

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論