搜尋
首頁後端開發Python教學python裝飾器-限制函數呼叫次數的方法(10s呼叫一次)

下面為大家分享一篇python裝飾器-限制函數呼叫次數的方法(10s呼叫一次),具有很好的參考價值,希望對大家有幫助。一起來看看吧

這是部落客最近一家大公司的面試題,寫一個裝飾器,限制函數每10s調用一次。當時是筆試的,只寫了大概的程式碼,回來後溫習了python裝飾器的基礎知識,把程式碼寫完了。決定寫篇部落格記錄下。

裝飾器分為帶參數得裝飾器以及不帶參數得裝飾器。

#不带参数的装饰器
@dec1
@dec2
def func():
  ...
#这个函数声明等价于
func = dec1(dec2(func))
#带参数的装饰器
@dec(some_args)
def func():
  ...
#这个函数声明等价于
func = dec(some_args)(func)

不帶參數的裝飾器需要注意的一些細節

1. 關於裝飾器函數(decorator)本身

因此一個裝飾器一般對應兩個函數,一個是decorator函數,用來進行一些初始化操作處理,一個是decorated_func用來實現對被裝飾的函數func的額外處理。並且為了保持對func的引用,decorated_func一般作為decorator的內部函數

#
def decorator(func):
  def decorator_func()
    func()
  return decorated_func

decorator函數只在函數宣告的時候被呼叫一次

裝飾器實際上是語法糖,在宣告函數之後就會被調用,產生decorated_func,並把func符號的引用替換為decorated_func。之後每次都呼叫func函數,實際呼叫的是decorated_func(這個很重要,裝飾之後,其實每次呼叫的是decorated_func)。

>>> def decorator(func):
...   def decorated_func():
...     func(1)
...   return decorated_func
... 
#声明时就被调用
>>> @decorator
... def func(x):
...   print x
... 
decorator being called 
#使用func()函数实际上使用的是decorated_func函数
>>> func()
1
>>> func.__name__
'decorated_func'

如果要保證傳回的decorated_func的函數名稱與func的函數名稱相同,應在decorator函數傳回decorated_func之前,加入decorated_func.name = func. name, 另外functools模組提供了wraps裝飾器,可以完成這一動作。

#@wraps(func)的操作相当于
#在return decorated_func之前,执行
#decorated_func.__name__ = func.__name__
#func作为装饰器参数传入, 
#decorated_func则作为wraps返回的函数的参数传入
>>> def decorator(func):
...   @wraps(func)
...   def decorated_func():
...     func(1)
...   return decorated_func
... 
#声明时就被调用
>>> @decorator
... def func(x):
...   print x
... 
decorator being called 
#使用func()函数实际上使用的是decorated_func函数
>>> func()
1
>>> func.__name__
'func'

decorator函數局部變數的妙用

因為closure的特性(詳見(1)部分閉包部分的詳解),decorator宣告的變數會被decorated_func.func_closure引用,所以呼叫了decorator方法結束之後,decorator方法的局部變數也不會被回收,因此可以用decorator方法的局部變數作為計數器,緩存等等。

值得注意的是,如果要改變變數的值,則變數一定要是可變對象,因此就算是計數器,也應當用列表來實現。且宣告一次函數呼叫一次decorator函數,所以不同函數的計數器之間互不衝突,例如:

#
#!/usr/bin/env python
#filename decorator.py
def decorator(func):
  #注意这里使用可变对象
  a = [0]
  def decorated_func(*args,**keyargs):
    func(*args, **keyargs)
    #因为闭包是浅拷贝,如果是不可变对象,每次调用完成后符号都会被清空,导致错误
    a[0] += 1
    print "%s have bing called %d times" % (func.__name__, a[0])
  return decorated_func
@decorator
def func(x):
  print x
@decorator
def theOtherFunc(x):
  print x

下面我們開始寫程式碼:

#coding=UTF-8
#!/usr/bin/env python
#filename decorator.py
import time
from functools import wraps
def decorator(func):
  "cache for function result, which is immutable with fixed arguments"
  print "initial cache for %s" % func.__name__
  cache = {}
  @wraps(func)
  def decorated_func(*args,**kwargs):
    # 函数的名称作为key
    key = func.__name__
    result = None
    #判断是否存在缓存
    if key in cache.keys():
      (result, updateTime) = cache[key]
      #过期时间固定为10秒
      if time.time() -updateTime < 10:
        print "limit call 10s", key
        result = updateTime
      else :
        print "cache expired !!! can call "
        result = None
    else:
      print "no cache for ", key
    #如果过期,或则没有缓存调用方法
    if result is None:
      result = func(*args, **kwargs)
      cache[key] = (result, time.time())
    return result
  return decorated_func
@decorator
def func(x):
  print &#39;call func&#39;

隨便測試了下,基本上沒有問題。

>>> from decorator import func
initial cache for func
>>> func(1)
no cache for func
call func
>>> func(1)
limit call 10s func
1488082913.239092
>>> func(1)
cache expired !!! can call
call func
>>> func(1)
limit call 10s func
1488082923.298204
>>> func(1)
cache expired !!! can call
call func
>>> func(1)
limit call 10s func
1488082935.165979
>>> func(1)
limit call 10s func
1488082935.165979

相關推薦:

python 限制函數呼叫次數

########

以上是python裝飾器-限制函數呼叫次數的方法(10s呼叫一次)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何將元素附加到Python數組?您如何將元素附加到Python數組?Apr 30, 2025 am 12:19 AM

Inpython,YouAppendElementStoAlistusingTheAppend()方法。 1)useappend()forsingleelements:my_list.append(4).2)useextend()orextend()或= formultiplelements:my_list.extend.extend(emote_list)ormy_list = [4,5,6] .3)useInsert()forspefificpositions:my_list.insert(1,5).beaware

您如何調試與Shebang有關的問題?您如何調試與Shebang有關的問題?Apr 30, 2025 am 12:17 AM

調試shebang問題的方法包括:1.檢查shebang行確保是腳本首行且無前置空格;2.驗證解釋器路徑是否正確;3.直接調用解釋器運行腳本以隔離shebang問題;4.使用strace或truss跟踪系統調用;5.檢查環境變量對shebang的影響。

如何從python數組中刪除元素?如何從python數組中刪除元素?Apr 30, 2025 am 12:16 AM

pythonlistscanbemanipulationusseveralmethodstoremovelements:1)theremove()MethodRemovestHefirStocCurrenceOfAstePecificiedValue.2)thepop()thepop()methodRemovesandReturnturnturnturnsanaNelementAgivenIndex.3)

可以在Python列表中存儲哪些數據類型?可以在Python列表中存儲哪些數據類型?Apr 30, 2025 am 12:07 AM

pythonlistscanstoreanydatate型,包括素,弦,浮子,布爾人,其他列表和迪克尼亞式

在Python列表上可以執行哪些常見操作?在Python列表上可以執行哪些常見操作?Apr 30, 2025 am 12:01 AM

pythristssupportnumeroferations:1)addingElementSwithAppend(),Extend(),andInsert()。 2)emovingItemSusingRemove(),pop(),andclear(),and clear()。 3)訪問andModifyingandmodifyingwithIndexingandSlicing.4)

如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境