国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 公安县| 二手房| 五原县| 曲水县| 苍梧县| 沽源县| 龙井市| 洛浦县| 东辽县| 寿光市| 通渭县| 双桥区| 和硕县| 石屏县| 大渡口区| 三江| 格尔木市| 洛扎县| 都江堰市| 通城县| 海城市| 高尔夫| 德兴市| 屯留县| 宁陕县| 邮箱| 寻甸| 定兴县| 赣州市| 曲靖市| 仁怀市| 全南县| 乌海市| 巴彦淖尔市| 城固县| 韶关市| 嘉荫县| 宁陵县| 宁强县| 惠来县| 梁平县|