午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

您的位置:首頁技術(shù)文章
文章詳情頁

深入了解Python裝飾器的高級用法

瀏覽:173日期:2022-07-14 10:28:26

原文地址https://www.codementor.io/python/tutorial/advanced-use-python-decorators-class-function

介紹

我寫這篇文章的主要目的是介紹裝飾器的高級用法。如果你對裝飾器知之甚少,或者對本文講到的知識點易混淆。我建議你復(fù)習(xí)下裝飾器基礎(chǔ)教程。本教程的目標(biāo)是介紹裝飾器的一些有趣的用法。特別是怎樣在類中使用裝飾器,怎樣給裝飾器傳遞額外的參數(shù)。

裝飾器 vs 裝飾器模式

Decorator模式是一個面向?qū)ο蟮脑O(shè)計模式,它允許動態(tài)地往現(xiàn)有的對象添加行為。當(dāng)你裝飾了一個對象,在某種程度上,你是在獨立于同一個類的其他實例的基礎(chǔ)上擴展其功能。Python裝飾器不是裝飾器模式的實現(xiàn),它在函數(shù)、方法定義的時候添加功能,而不是在運行的時候添加。Decorator設(shè)計模式本身可以在Python中實現(xiàn),因為Python是動態(tài)編程語言,所以沒有必要這樣做。

一個基礎(chǔ)的裝飾器

這是裝飾器的最簡單例子,在繼續(xù)往下面閱讀之前請確保理解此段代碼。如果你需要更多關(guān)于此代碼的解釋,請復(fù)習(xí)下基礎(chǔ)裝飾器教程。

def time_this(original_function): def new_function(*args, **kwargs): import datetime before = datetime.datetime.now() x = original_function(*args, **kwargs) after = datetime.datetime.now() print('Elapsed Time = {}'.format(after-before)) return x return new_function@time_thisdef func_a(stuff): import time time.sleep(stuff) func_a(3)# out:Elapsed Time = 0:00:03.012472

帶參數(shù)的裝飾器

有時候帶參數(shù)的裝飾器會非常有用,這種技術(shù)經(jīng)常用在函數(shù)注冊中。在web框架Pyramid中經(jīng)常有用到,例如:

@view_config(route_name=’home’, renderer=’templates/mytemplate.pt’)def my_view(request): return {’project’: ’hello decorators’}

比方說,我們有一個用戶可以登錄并且可以和用戶交互的GUI應(yīng)用程序。用戶和GUI界面的交互觸發(fā)事件,導(dǎo)致Python函數(shù)執(zhí)行。假設(shè)有許多使用該圖形界面的用戶,他們各自的權(quán)限級別差異很大,不同的功能執(zhí)行需要不同的權(quán)限。比如,考慮以下功能:

# 假設(shè)這些函數(shù)是存在的def current_user_id(): ''' this function returns the current logged in user id, if the use is not authenticated the return None '''def get_permissions(iUserId): ''' returns a list of permission strings for the given user. For example [’logged_in’,’administrator’,’premium_member’] '''# 在這些函數(shù)中我們需要實現(xiàn)權(quán)限檢查 def delete_user(iUserId): ''' delete the user with the given Id. This function is only accessable to users with administrator permissions ''' def new_game(): ''' any logged in user can start a new game ''' def premium_checkpoint(): ''' save the game progress, only accessable to premium members '''

一種實現(xiàn)這些權(quán)限檢查的方式是實現(xiàn)多個裝飾器,比如:

def requires_admin(fn): def ret_fn(*args,**kwargs): lPermissions = get_permissions(current_user_id()) if ’administrator’ in lPermissions: return fn(*args,**kwargs) else: raise Exception('Not allowed') return ret_fndef requires_logged_in(fn): def ret_fn(*args,**kwargs): lPermissions = get_permissions(current_user_id()) if ’logged_in’ in lPermissions: return fn(*args,**kwargs) else: raise Exception('Not allowed') return ret_fn def requires_premium_member(fn): def ret_fn(*args,**kwargs): lPermissions = get_permissions(current_user_id()) if ’premium_member’ in lPermissions: return fn(*args,**kwargs) else: raise Exception('Not allowed') return ret_fn @requires_admindef delete_user(iUserId): ''' delete the user with the given Id. This function is only accessable to users with administrator permissions '''@requires_logged_indef new_game(): ''' any logged in user can start a new game ''' @requires_premium_memberdef premium_checkpoint(): ''' save the game progress, only accessable to premium members '''

但是,這太可怕了。這需要大量的復(fù)制粘貼,每個裝飾器需要一個不同的名字,如果有任何關(guān)于權(quán)限檢查的改變,每個裝飾器都需要修改。就沒有一個裝飾器把以上三個裝飾器的工作都干了的嗎?

為了解決此問題,我們需要一個返回裝飾器的函數(shù):

def requires_permission(sPermission): def decorator(fn): def decorated(*args,**kwargs): lPermissions = get_permissions(current_user_id()) if sPermission in lPermissions: return fn(*args,**kwargs) raise Exception('permission denied') return decorated return decoratordef get_permissions(iUserId): # this is here so that the decorator doesn’t throw NameErrors return [’logged_in’,]def current_user_id(): #ditto on the NameErrors return 1#and now we can decorate stuff... @requires_permission(’administrator’)def delete_user(iUserId): ''' delete the user with the given Id. This function is only accessible to users with administrator permissions '''@requires_permission(’logged_in’)def new_game(): ''' any logged in user can start a new game ''' @requires_permission(’premium_member’)def premium_checkpoint(): ''' save the game progress, only accessable to premium members '''

嘗試一下調(diào)用delete_user,new name和premium_checkpoint然后看看發(fā)生了什么。premium_checkpoint 和delete_user 產(chǎn)生了一個“permission denied”的異常,new_game執(zhí)行正常。下面是帶參數(shù)裝飾的一般形式,和例子的使用:

def outer_decorator(*outer_args,**outer_kwargs): def decorator(fn): def decorated(*args,**kwargs): do_something(*outer_args,**outer_kwargs) return fn(*args,**kwargs) return decorated return decorator @outer_decorator(1,2,3)def foo(a,b,c): print(a) print(b) print(c)foo()

等價于:

def decorator(fn): def decorated(*args,**kwargs): do_something(1,2,3) return fn(*args,**kwargs) return decorated return decorator @decoratordef foo(a,b,c): print(a) print(b) print(c)foo()

類裝飾器

裝飾器不僅可以修飾函數(shù),還可以對類進行裝飾。比如說,我們有一個類,該類含有許多重要的方法,我們需要記錄每一個方法執(zhí)行的時間。我們可以使用上述的time_this裝飾此類:

class ImportantStuff(object): @time_this def do_stuff_1(self): pass@time_this def do_stuff_2(self): pass@time_this def do_stuff_3(self): pass

此方法可以運行正常。但是在該類中存在許多多余的代碼,如果我們想建立更多的類方法并且遺忘了裝飾其中的一個方法,如果我們不想裝飾該類中的方法了,會發(fā)生什么樣的情況呢?這可能會存在出現(xiàn)認為錯誤的空間,如果寫成這樣會更有好:

@time_all_class_methodsclass ImportantStuff: def do_stuff_1(self): pass def do_stuff_2(self): pass def do_stuff_3(self): pass

等價于:

class ImportantStuff: def do_stuff_1(self): pass def do_stuff_2(self): pass def do_stuff_3(self): passImportantStuff = time_all_class_methods(ImportantStuff)

那么time_all_class_methods是怎么工作的呢?首先,我們需要采用一個類作為參數(shù),然后返回一個類,我們也要知道返回的類的功能應(yīng)該和原始類ImportantStuff功能一樣。也就是說,我們?nèi)匀幌M鲋匾氖虑椋覀兿M涗浵旅總€步驟發(fā)生的時間。我們寫成這樣:

def time_this(original_function): print('decorating') def new_function(*args,**kwargs): print('starting timer') import datetime before = datetime.datetime.now() x = original_function(*args,**kwargs) after = datetime.datetime.now() print('Elapsed Time = {0}'.format(after-before)) return x return new_functiondef time_all_class_methods(Cls): class NewCls: def __init__(self,*args,**kwargs): self.oInstance = Cls(*args,**kwargs) def __getattribute__(self,s): try: x = super(NewCls,self).__getattribute__(s) except AttributeError: pass else: return x x = self.oInstance.__getattribute__(s) if type(x) == type(self.__init__): return time_this(x) else: return x return NewCls@time_all_class_methodsclass Foo: def a(self): print('entering a') import time time.sleep(3) print('exiting a')oF = Foo()oF.a()# out:decoratingstarting timerentering aexiting aElapsed Time = 0:00:03.006767

總結(jié)

在此篇教程中,我們給大家展示了一些Python裝飾器使用的技巧-我們介紹了怎么樣把參數(shù)傳遞給裝飾器,怎樣裝飾類。但是這僅僅是冰山一角。除了本文介紹的之外,還有其他好多裝飾器的使用方法,我們甚至可以使用裝飾器裝飾裝飾器(如果你有機會使用到它,這可能是一個做全面檢查的好方法)。Python有一些內(nèi)置的裝飾器,比如:staticmethod,classmethod閱讀完本文還需要學(xué)習(xí)什么呢?通常是沒有比我在文章中展示的裝飾器更復(fù)雜的了,如果你有興趣學(xué)習(xí)更多關(guān)于改變類功能的方法,我建議您閱讀下繼承和OOP設(shè)計原則。或者你可以試試閱讀一下元類。

以上就是深入了解Python裝飾器的高級用法的詳細內(nèi)容,更多關(guān)于Python裝飾器的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 中文字幕一区二区三区不卡 | 成人69视频 | 一级片成人 | 亚洲不卡在线播放 | 亚洲午夜久久久 | 看毛片视频 | 欧美一区二区三区在线观看视频 | 毛片小视频| 精品国产一区在线 | 国产精品永久免费观看 | 日日日夜夜操 | 亚洲一区久久久 | 欧美a∨亚洲欧美亚洲 | www.av网址| 色中色在线视频 | 日韩资源在线 | 调教驯服丰满美艳麻麻在线视频 | 久久精品国产99国产 | 日韩黄色片网站 | 91视频精品 | 青青综合网 | 欧美日韩精品免费观看 | 亚洲天堂成人在线 | 99爱精品视频 | 日本一区二区三区在线观看视频 | 欧美一区一区 | 久久精品在线 | 国产日韩在线视频 | 国产一区免费看 | xxxx性欧美| 久久久777 | 久久久久久九九九九 | 九九热视频在线 | 91久久国产精品 | 国产日韩免费 | 免费日韩精品 | 亚洲精品91在线 | 国产jizz18女人高潮 | 91丨九色丨蝌蚪丨少妇在线观看 | 四虎黄色影视 | 亚洲香蕉久久 |