python裝飾器練習

2022-08-11 23:39:21 字數 2322 閱讀 6113

1、編寫裝飾器,為多個函式加上認證功能(使用者的賬戶密碼**檔案)

要求登入成功一次,後續的函式都無需再輸入使用者名稱和密碼

flag =false

deflogin(func):

def inner(*args,**kwargs):

global

flag

"""登入程式

"""if

flag:

ret = func(*args,**kwargs)

return

ret

else

: username = input('

you name: ')

password = input('

you password:')

if username == 'dj'

and password == '

123'

: flag =true

ret = func(*args, **kwargs)

return

ret

else

:

print('

logining error')

return

inner

@login

#shoplistadd = login(shoplistadd)

defshoplistadd():

print('

增加物品')

@login

defshoplistdel():

print('

刪除物品')

shoplistadd()

shoplistdel()

2、編寫裝飾器,為多個函式加上記錄呼叫功能,要求每次呼叫函式都將被呼叫的函式名稱寫入檔案

def

log(func):

def inner(*args,**kwargs):

with open(

'log

',mode='

a',encoding='

utf-8

') as f:

f.write(func.

__name__+'\n'

) ret = func(*args,**kwargs)

return

ret

return

inner

@log

#shoplistadd = log(shoplistadd)

defshoplistadd():

print('

增加一件物品')

@log

#shoplistdel = log(shoplistdel)

defshoplistdel():

print('

刪除一件物品')

shoplistadd()

shoplistdel()

import

osfrom urllib.request import

urlopen

defcache(func):

def inner(*args,**kwargs):

if os.path.getsize('

web_cache'):

with open(

'web_cache

','rb

') as f:

return

f.read()

ret = func(*args,**kwargs) #

get()

with open('

web_cache

','wb

') as f:

f.write(b

'*********

'+ret)

return

ret

return

inner

@cache

defget(url):

code =urlopen(url).read

return

code

ret = get('

')print(ret)

python 裝飾器練習

import time import functools def add log fun functools.wraps fun start time time.time res fun args,kwargs end time time.time fun.name end time start t...

Python裝飾器練習

看廖下廖大的裝飾器的文件 寫了練習 設計乙個decorator,它可作用於任何函式上,並列印該函式的執行時間 coding utf 8 import time,functools def metric fn time1 time.time ret fn args,kw time2 time.time...

python裝飾器練習

判斷是否是root使用者 def hahaha fc def woshinima args if args 0 root args是列表,儘管只有乙個元素,但是必須是 0 return fc args print error return woshinima hahaha def add stude...