人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

Python裝飾器的兩種使用心得

發(fā)布日期:2021-12-29 02:21 | 文章來(lái)源:源碼中國(guó)

裝飾器的基礎(chǔ)使用(裝飾帶參函數(shù))

def decorator(func):
 def inner(info):
  print('inner')
  func(info)
 return inner
@decorator
def show_info(info):
 print(info)
show_info('hello')

防止裝飾器改變裝飾函數(shù)名稱(chēng)

裝飾器在裝飾函數(shù)的時(shí)候由于返回的是inner的函數(shù)地址,所以函數(shù)的名稱(chēng)也會(huì)改變 show_info.__name__會(huì)變成inner,防止這種現(xiàn)象可以使用functools

import functools
def decorator(func):
	@functools.wraps(func)
 def inner(info):
  print('inner')
  func(info)
 return inner
@decorator
def show_info(info):
 print(info)
show_info('hello')

這樣寫(xiě)就不會(huì)改變被裝飾函數(shù)的名稱(chēng)

裝飾器動(dòng)態(tài)注冊(cè)函數(shù)

此方法在Flask框架的app.Route()的源碼中體現(xiàn)

class Commands(object):
 def __init__(self):
  self.cmd = {}
 def regist_cmd(self, name: str) -> None:
  def decorator(func):
self.cmd[name] = func
print('func:',func)
return func
  return decorator
commands = Commands()
# 使得s1的值指向show_h的函數(shù)地址
@commands.regist_cmd('s1')
def show_h():
 print('show_h')
# 使得s2的值指向show_e的函數(shù)地址
@commands.regist_cmd('s2')
def show_e():
 print('show_e')
func = commands.cmd['s1']
func()

個(gè)人心得

在閱讀裝飾器代碼時(shí)可以使用加(func_name)的方式
以為例

@commands.regist_cmd('s2')
def show_e():
 print('show_e')

即 show_e = commands.regist_cmd('s2')(show_e)

到此這篇關(guān)于Python裝飾器的兩種使用的文章就介紹到這了,更多相關(guān)Python裝飾器使用內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!

版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開(kāi)通

自選配置、實(shí)時(shí)開(kāi)通

免備案

全球線(xiàn)路精選!

全天候客戶(hù)服務(wù)

7x24全年不間斷在線(xiàn)

專(zhuān)屬顧問(wèn)服務(wù)

1對(duì)1客戶(hù)咨詢(xún)顧問(wèn)

在線(xiàn)
客服

在線(xiàn)客服:7*24小時(shí)在線(xiàn)

客服
熱線(xiàn)

400-630-3752
7*24小時(shí)客服服務(wù)熱線(xiàn)

關(guān)注
微信

關(guān)注官方微信
頂部