python的裝飾器

什麼是python的裝飾器?python

  網絡上的定義:網絡

    裝飾器就是一函數,用來包裝函數的函數,用來修飾原函數,將其從新賦值給原來的標識符,並永久的喪失原函數的引用。app

  在google上搜索下python 裝飾器 能夠搜索到不少關於不少的關於裝飾器的文章,一個很簡單,最能說明裝飾器的例子以下:函數

#-*- coding: UTF-8 -*-
import time
 
def foo():
    print 'in foo()'
 
# 定義一個計時器,傳入一個,並返回另外一個附加了計時功能的方法
def timeit(func):
     
    # 定義一個內嵌的包裝函數,給傳入的函數加上計時功能的包裝
    def wrapper():
        start = time.clock()
        func()
        end =time.clock()
        print 'used:', end - start
     
    # 將包裝後的函數返回
    return wrapper
 
foo = timeit(foo)
foo()

python中提供了一個@符號的語法糖,用來簡化上面的代碼,他們的做用同樣google

import time
 
def timeit(func):
    def wrapper():
        start = time.clock()
        func()
        end =time.clock()
        print 'used:', end - start
    return wrapper
 
@timeit
def foo():
    print 'in foo()'
 
foo()

這2段的代碼是同樣的,等價的。spa

內置的3個裝飾器,他們分別是staticmethod,classmethod,property,他們的做用是分別把類中定義的方法變成靜態方法,類方法和屬性,以下:code

class Rabbit(object):
     
    def __init__(self, name):
        self._name = name
     
    @staticmethod
    def newRabbit(name):
        return Rabbit(name)
     
    @classmethod
    def newRabbit2(cls):
        return Rabbit('')
     
    @property
    def name(self):
        return self._name

裝飾器的嵌套:blog

就一個規律:嵌套的順序和代碼的順序是相反的。utf-8

也是來看一個例子:it

#!/usr/bin/python
# -*- coding: utf-8 -*-

def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makebold
@makeitalic
def hello():
    return "hello world"

print hello()

返回的結果是:

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

爲何是這個結果呢?

1.首先hello函數通過makeitalic 函數的裝飾,變成了這個結果<i>hello world</i>

2.而後再通過makebold函數的裝飾,變成了<b><i>hello world</i></b>,這個理解起來很簡單。

 ---end---  

相關文章
相關標籤/搜索