python裝飾器使用方法實例
什么是python的裝飾器?
網(wǎng)絡上的定義:
裝飾器就是一函數(shù),用來包裝函數(shù)的函數(shù),用來修飾原函數(shù),將其重新賦值給原來的標識符,并永久的喪失原函數(shù)的引用。
最能說明裝飾器的例子如下:
#-*- coding: UTF-8 -*-
import time
def foo():
print 'in foo()'
# 定義一個計時器,傳入一個,并返回另一個附加了計時功能的方法
def timeit(func):
# 定義一個內(nèi)嵌的包裝函數(shù),給傳入的函數(shù)加上計時功能的包裝
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
# 將包裝后的函數(shù)返回
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段的代碼是一樣的,等價的。
內(nèi)置的3個裝飾器,他們分別是staticmethod,classmethod,property,他們的作用是分別把類中定義的方法變成靜態(tài)方法,類方法和屬性,如下:
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
裝飾器的嵌套:
就一個規(guī)律:嵌套的順序和代碼的順序是相反的。
也是來看一個例子:
#!/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()
返回的結(jié)果是:
<b><i>hello world</i></b>
為什么是這個結(jié)果呢?
1.首先hello函數(shù)經(jīng)過makeitalic 函數(shù)的裝飾,變成了這個結(jié)果<i>hello world</i>
2.然后再經(jīng)過makebold函數(shù)的裝飾,變成了<b><i>hello world</i></b>,這個理解起來很簡單。
相關文章
jupyter?notebook內(nèi)核啟動失敗問題及解決方法
這篇文章主要介紹了解決jupyter?notebook內(nèi)核啟動失敗問題,本文給大家介紹了問題原因分析及解決方案,圖文并茂的形式給大家介紹的非常詳細,需要的朋友可以參考下2022-04-04
matlab和Excel的數(shù)據(jù)交互操作(非xlsread和xlswrite)
在使用MATLAB時,可能會遇到很多表格數(shù)據(jù)的處理,有時MATLAB也需要利用現(xiàn)存的表格數(shù)據(jù)實現(xiàn)操作目的,下面這篇文章主要給大家介紹了關于matlab和Excel的交互操作的相關資料,非xlsread和xlswrite,需要的朋友可以參考下2021-08-08

