python裝飾器實現函式註冊和類裝飾器

2021-10-04 03:30:37 字數 2746 閱讀 7179

******01 一般情況下都是使用函式作為裝飾器,其實class也是可以的,function是callable物件,class只有重寫了__call__方法後,它的例項物件也就是callable物件了。

******02 裝飾器的巢狀:就乙個規律:巢狀的順序和**的順序是相反的。

class functionmanager:

def __init__(self):

print(

"初始化"

) self.functions =

def execute_all(self):

for func in self.functions:

func(

) def register(self, func):

fm = functionmanager(

)@fm.register

def t1(

): print(

"t1"

)@fm.register

def t2(

): print(

"t2"

)@fm.register

def t3(

): print(

"t3"

)fm.excute_all(

)# 結果如下:

初始化t1

t2t3

def class_info(

): print(cls.__name__)

#print(cls.__dict__)

@class_info(

)# test = class_info(test)

class test:

a = 1

b ="123"

c =["66","666"

] d =

輸出結果:

test

三 函式和類分別做修飾器

******本質上裝飾器就是乙個返回函式的高階函式,它接收乙個函式,並返回乙個函式,用法就是在被裝飾的函式上面加上@裝飾器函式名。

3.1 函式做修飾器, 類被修飾

def wrap(tmp_obj):

print(

"裝飾器------"

) tmp_obj.x = 1

tmp_obj.y = 3

tmp_obj.z = 5

return tmp_obj

******@wrap #將類foo作為乙個引數傳入[類位址]修飾器wrap,返回該物件,同時把新物件重新命名為foo, 即foo = wrap(foo)

class foo:

pass

輸出結果:

裝飾器------

print(foo.__dict__)

#輸出結果,新的foo類新增了x,y,z屬性

3.2 函式做修飾器,另乙個函式做被修飾器

# 函式可以作為乙個物件,也有__dict__方法

def wrap(obj):

print(

"裝飾器------"

) obj.x = 1

obj.y = 3

obj.z = 5

return obj

@wrap # test = wrap(test)

def test(

): print(

"test ------ "

)test.x = 10 # test的x屬性被重新賦值

3.3 類做修飾器,函式被修飾

import

time

class test:

def __init__(self,func):

self.func = func

def __call__(self,*args,**kwargs):

print(

"123"

) start_time = time.time(

) self.func(*args,**kwargs)

time.sleep(2)

end_time = time.time(

)return

(end_time - start_time)

******@test # test1 = test(test1) test1例項化test 傳入test1的函式位址

def test1(a):

print(

"測試一下類裝飾器%s" % a)

test1(

"123"

)# __call__():給例項化賦予函式功能,執行例項化後的test1 就等價於執行__call__()

3.4 類做修飾器,類被修飾

class showclassname(object):

def __init__(self, cls):

self._cls = cls

def __call__(self, a):

print(

"class name:", self._cls.__name__)

@showclassname

class foobar(object):

def __init__(self, a):

self.value = a

def fun(self):

print(self.value)

a = foobar(

"xiemanr"

)a.fun(

)

reference:

python裝飾器 函式裝飾器,類裝飾器

只要實現此 模式,這個obj就叫乙個裝飾器 參考 函式裝飾器 例子 def decorator func def inner args,kwargs print before.res func args,kwargs print after.return res return inner decor...

python 裝飾器 函式裝飾器 類裝飾器

python函式裝飾器和類裝飾器筆記.usr bin env python coding utf 8 author ivan file decorators.py version from functools import wraps 裝飾器 目的是為了給函式新增附加功能 1.不帶引數裝飾器 此方式...

python裝飾器 裝飾器工廠函式

使用裝飾器實現如下所示的列印 小白聯盟def printequel func1 def inner1 print 15 func1 return inner1 def printstar func2 def inner2 print 15 func2 return inner2 printequel...