亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python中使用裝飾器時需要注意的一些問題

 更新時間:2015年05月11日 10:01:59   作者:曾靈敏  
這篇文章主要介紹了Python中使用裝飾器時需要注意的一些問題,裝飾器是Python學習進階中的重要知識點,需要的朋友可以參考下

裝飾器基本概念

大家都知道裝飾器是一個很著名的設計模式,經常被用于AOP(面向切面編程)的場景,較為經典的有插入日志,性能測試,事務處理,Web權限校驗,Cache等。

Python語言本身提供了裝飾器語法(@),典型的裝飾器實現(xiàn)如下:

  

 @function_wrapper
  def function():
    pass

@實際上是python2.4才提出的語法糖,針對python2.4以前的版本有另一種等價的實現(xiàn):

  def function():
    pass

  function = function_wrapper(function)

裝飾器的兩種實現(xiàn)

函數(shù)包裝器 - 經典實現(xiàn)

   

def function_wrapper(wrapped):
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)
    return _wrapper 

  @function_wrapper
  def function():
    pass

類包裝器 - 易于理解

 

  class function_wrapper(object):
    def __init__(self, wrapped):
      self.wrapped = wrapped
    def __call__(self, *args, **kwargs):
      return self.wrapped(*args, **kwargs)

  @function_wrapper
  def function():
    pass

函數(shù)(function)自省

當我們談到一個函數(shù)時,通常希望這個函數(shù)的屬性像其文檔上描述的那樣,是被明確定義的,例如__name__和__doc__ 。

針對某個函數(shù)應用裝飾器時,這個函數(shù)的屬性就會發(fā)生變化,但這并不是我們所期望的。

  

 def function_wrapper(wrapped):
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)
    return _wrapper 

  @function_wrapper
  def function():
    pass 

  >>> print(function.__name__)
  _wrapper

python標準庫提供了functools.wraps(),來解決這個問題。

  import functools 

  def function_wrapper(wrapped):
    @functools.wraps(wrapped)
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)
    return _wrapper 

  @function_wrapper
  def function():
    pass 

  >>> print(function.__name__)
  function

然而,當我們想要獲取被包裝函數(shù)的參數(shù)(argument)或源代碼(source code)時,同樣不能得到我們想要的結果。

  import inspect 

  def function_wrapper(wrapped): ...

  @function_wrapper
  def function(arg1, arg2): pass 

  >>> print(inspect.getargspec(function))
  ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)

  >>> print(inspect.getsource(function))
    @functools.wraps(wrapped)
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)

包裝類方法(@classmethod)

當包裝器(@function_wrapper)被應用于@classmethod時,將會拋出如下異常:

  

 class Class(object):
    @function_wrapper
    @classmethod
    def cmethod(cls):
      pass 

  Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 3, in Class
   File "<stdin>", line 2, in wrapper
   File ".../functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
  AttributeError: 'classmethod' object has no attribute '__module__'

因為@classmethod在實現(xiàn)時,缺少functools.update_wrapper需要的某些屬性。這是functools.update_wrapper在python2中的bug,3.2版本已被修復,參考http://bugs.python.org/issue3445。

然而,在python3下執(zhí)行,另一個問題出現(xiàn)了:

   

class Class(object):
    @function_wrapper
    @classmethod
    def cmethod(cls):
      pass 

  >>> Class.cmethod() 
  Traceback (most recent call last):
   File "classmethod.py", line 15, in <module>
    Class.cmethod()
   File "classmethod.py", line 6, in _wrapper
    return wrapped(*args, **kwargs)
  TypeError: 'classmethod' object is not callable

這是因為包裝器認定被包裝的函數(shù)(@classmethod)是可以直接被調用的,但事實并不一定是這樣的。被包裝的函數(shù)實際上可能是描述符(descriptor),意味著為了使其可調用,該函數(shù)(描述符)必須被正確地綁定到某個實例上。關于描述符的定義,可以參考https://docs.python.org/2/howto/descriptor.html。
總結 - 簡單并不意味著正確

盡管大家實現(xiàn)裝飾器所用的方法通常都很簡單,但這并不意味著它們一定是正確的并且始終能正常工作。

如同上面我們所看到的,functools.wraps()可以幫我們解決__name__和__doc__ 的問題,但對于獲取函數(shù)的參數(shù)(argument)或源代碼(source code)則束手無策。

以上問題,wrapt都可以幫忙解決,詳細用法可參考其官方文檔:http://wrapt.readthedocs.org

相關文章

  • python實現(xiàn)兩張圖片的像素融合

    python實現(xiàn)兩張圖片的像素融合

    這篇文章主要為大家詳細介紹了python實現(xiàn)兩張圖片的像素融合,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-02-02
  • python項目--使用Tkinter的日歷GUI應用程序

    python項目--使用Tkinter的日歷GUI應用程序

    在 Python 中,我們可以使用 Tkinter 制作 GUI。如果你非常有想象力和創(chuàng)造力,你可以用 Tkinter 做出很多有趣的東西,希望本篇文章能夠幫到你
    2021-08-08
  • 用Python實現(xiàn)一個模仿UP主彈幕控制的直播間功能

    用Python實現(xiàn)一個模仿UP主彈幕控制的直播間功能

    up主通過代碼實現(xiàn)了實時讀取直播間里的彈幕內容,進而控制自己的電腦,把彈幕翻譯成指令操控《賽博朋克2077》游戲,這篇文章主要介紹了用Python實現(xiàn)一個模仿UP主彈幕控制的直播間功能,需要的朋友可以參考下
    2021-12-12
  • Python內置數(shù)據類型詳解

    Python內置數(shù)據類型詳解

    這篇文章主要介紹了Python內置數(shù)據類型,需要的朋友可以參考下
    2014-08-08
  • Django中使用Json返回數(shù)據的實現(xiàn)方法

    Django中使用Json返回數(shù)據的實現(xiàn)方法

    這篇文章主要介紹了Django中使用Json返回數(shù)據的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-06-06
  • python將音頻進行變速的操作方法

    python將音頻進行變速的操作方法

    這篇文章主要介紹了python將音頻進行變速的操作方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-04-04
  • TensorFlow實現(xiàn)指數(shù)衰減學習率的方法

    TensorFlow實現(xiàn)指數(shù)衰減學習率的方法

    這篇文章主要介紹了TensorFlow實現(xiàn)指數(shù)衰減學習率的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-02-02
  • python中numpy?常用操作總結

    python中numpy?常用操作總結

    這篇文章主要介紹了python中numpy常用操作總結,NumPy是Python語言的一個擴充程序庫,支持大量高維度數(shù)組與矩陣運算,此外也針對數(shù)組運算提供大量的數(shù)學函數(shù)庫
    2022-09-09
  • python中的split()函數(shù)和os.path.split()函數(shù)使用詳解

    python中的split()函數(shù)和os.path.split()函數(shù)使用詳解

    今天小編就為大家分享一篇python中的split()函數(shù)和os.path.split()函數(shù)使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • 使用ChatGPT來自動化Python任務

    使用ChatGPT來自動化Python任務

    這篇文章主要介紹了使用ChatGPT來自動化Python任務的相關資料,需要的朋友可以參考下
    2022-12-12

最新評論