国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中的各種裝飾器詳解

2020-02-23 00:38:12
字體:
供稿:網(wǎng)友

Python裝飾器,分兩部分,一是裝飾器本身的定義,一是被裝飾器對(duì)象的定義。

一、函數(shù)式裝飾器:裝飾器本身是一個(gè)函數(shù)。

1.裝飾函數(shù):被裝飾對(duì)象是一個(gè)函數(shù)

[1]裝飾器無參數(shù):

a.被裝飾對(duì)象無參數(shù):
代碼如下:
>>> def test(func):
    def _test():
        print 'Call the function %s().'%func.func_name
        return func()
    return _test

>>> @test
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>>

b.被裝飾對(duì)象有參數(shù):
代碼如下:
>>> def test(func):
    def _test(*args,**kw):
        print 'Call the function %s().'%func.func_name
        return func(*args,**kw)
    return _test

>>> @test
def left(Str,Len):
    #The parameters of _test can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call the function left().
'hello'
>>>

[2]裝飾器有參數(shù):

a.被裝飾對(duì)象無參數(shù):
代碼如下:
>>> def test(printResult=False):
    def _test(func):
        def __test():
            print 'Call the function %s().'%func.func_name
            if printResult:
                print func()
            else:
                return func()
        return __test
    return _test

>>> @test(True)
def say():return 'hello world'

>>> say()
Call the function say().
hello world
>>> @test(False)
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>> @test()
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>> @test
def say():return 'hello world'

>>> say()

Traceback (most recent call last):
  File "<pyshell#224>", line 1, in <module>
    say()
TypeError: _test() takes exactly 1 argument (0 given)
>>>

由上面這段代碼中的最后兩個(gè)例子可知:當(dāng)裝飾器有參數(shù)時(shí),即使你啟用裝飾器的默認(rèn)參數(shù),不另外傳遞新值進(jìn)去,也必須有一對(duì)括號(hào),否則編譯器會(huì)直接將func傳遞給test(),而不是傳遞給_test()

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 抚远县| 马关县| 长春市| 金堂县| 三原县| 廉江市| 神池县| 东兴市| 布拖县| 昆明市| 济源市| 祁连县| 信丰县| 泸溪县| 清新县| 平顶山市| 河东区| 六盘水市| 陆川县| 龙胜| 林甸县| 江城| 澳门| 贡嘎县| 天津市| 如东县| 天柱县| 衡东县| 绍兴县| 南昌市| 云霄县| 专栏| 卫辉市| 永仁县| 高尔夫| 新巴尔虎右旗| 天峻县| 延长县| 贞丰县| 永修县| 鄂托克前旗|