Python學習筆記--裝飾器/decorator

參考博文:

Python裝飾器與面向切面編程

Python裝飾器學習(九步入門)


測試程序:

1. 原函數功能爲輸出名字。現需求:不改變原函數內容,爲其添加額外功能--輸出名字前先輸出‘Hi there!’。此處使用了基本的裝飾器用法。

def sayName():
        print 'My name is: Stephen!'

def sayHi(func):
        def wrapper():
                print 'Hi there!'
                func()
        return wrapper

sayName = sayHi(sayName)
sayName()

Result:

stephen@Ubuntu01:~/project/stu905/day4$ python decorator_test.py 
Hi there!
My name is: Stephen!



2. 與例1類似,只不過使用了語法糖。

def sayHi(func):
        def wrapper():
                print 'Hi there!'
                func()
                print 'Goodbye!'
        return wrapper

@sayHi
def myName():
        print 'My name is: Stephen'

myName()

Result:

stephen@Ubuntu01:~/project/stu905/day4$ python sayhi.py 
Hi there!
My name is: Stephen
Goodbye!


3. 嘗試了下原函數帶參數及返回值的情況。原函數爲顯示具體年份是否爲閏年,要求添加額外功能:輸出結果前先讀取年份並且輸出它。

def printYear(func):
        def wrapper(y):
                print 'The year you have enter: %d' % y
                ret = func(y)
                return ret
        return wrapper

@printYear
def isLeapYear(year):
        Leap = False
        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
                Leap = True
        return Leap

print '2014 is leap year? %s' % isLeapYear(2014)
print '2012 is leap year? %s' % isLeapYear(2012)

Result:

stephen@Ubuntu01:~/project/stu905/day4$ python leap_year.py 
The year you have enter: 2014
2014 is leap year? False
The year you have enter: 2012
2012 is leap year? True





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章