python裝飾器使用方法執行個體_python

來源:互聯網
上載者:User

什麼是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中提供了一個@符號的文法糖,用來簡化上面的代碼,他們的作用一樣

複製代碼 代碼如下:

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段的代碼是一樣的,等價的。

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

複製代碼 代碼如下:

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

裝飾器的嵌套:
就一個規律:嵌套的順序和代碼的順序是相反的。
也是來看一個例子:

複製代碼 代碼如下:

#!/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>,這個理解起來很簡單。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.