python中裝飾器

2021-09-14 06:42:26 字數 2422 閱讀 3368

#對修改是封閉的,對擴充套件是開放的

import time

def f1():

# print(time.time())

print('this is a function...')

def f2():

print('this is a function...')

# print(time.time())

# f1()

def print_current_time(func):

print(time.time())

func()

print_current_time(f1)

print_current_time(f2)

結果為:

1554147010.7528

this is a function...

1554147010.7528443

this is a function...

利用裝飾器實現

import time

def decorator(func):

print(time.time()) #列印系統執行時間,時間從1970.1.1開始

func()

@decorator

def f1():

print('this is a function...')

def f2():

print('this is a function...')

f1()

f2() ##函式f2沒有加裝飾器

結果為:

1554147157.1240797

this is a function...

this is a function...

import time

def decorator(func):

print(time.time())

func(*args)

@decorator

def f1(func_name):

print('this is a function ' + func_name)

@decorator

def f2(func_name1,func_name2):

print('this is a function ' + func_name1)

print('this is a function ' + func_name2)

f1('test')

f2('test1','test2')

結果為:

1554147365.67018

this is a function test

1554147365.6703033

this is a function test1

this is a function test2

import time

def decorator(func):

def warpper(*args,**kwargs):

print(time.time())

func(*args,**kwargs)

return warpper

@decorator

def f1(func_name):

print('this is a function ' + func_name)

@decorator

def f2(func_name1,func_name2):

print('this is a function ' + func_name1)

print('this is a function ' + func_name2)

@decorator

def f3(func_name1,func_name2,**kwargs):

print('this is a function ' + func_name1)

print('this is a function ' + func_name2)

print(kwargs)

f1('test')

f2('test1','test2')

f3('test1','test2',a=1,b=2,c='westos')

結果為:

1554147466.7343357

this is a function test

1554147466.7344415

this is a function test1

this is a function test2

1554147466.7344847

this is a function test1

this is a function test2

python中裝飾器詳解

最新學了裝飾器,有乙個疑問一直困擾我,思考了幾天,終於明白。首先,展示正常的裝飾器 允許向乙個現有的物件新增新的功能,同時又不改變其結構,就是給函式穿個衣服,但是不改變函式 該如何寫?def log func print call s func.name return func args,kw 依照...

python中裝飾器理解

裝飾器 decorators 是 python 的乙個重要部分。簡單地說 他們是修改其他函式的功能的函式。他們有助於讓我們的 更簡短!由於函式也是乙個物件,而且函式物件可以被賦值給變數,所以,通過變數也能呼叫該函式。def now print 2015 3 25 f now f 2015 3 25 ...

Python中裝飾器的使用

在學習cs20si中遇到了裝飾器,所以這裡介紹下裝飾器decorator的使用。主要內容依據 python中,所有的東西都是物件,乙個函式可以被賦到變數中,傳遞給另乙個函式,或者被其他函式作為返回值。python的裝飾器就是乙個函式,接受函式作為引數,並且用另乙個函式作返回值。import time...