理解Python類裝飾器 call

2021-08-17 22:11:53 字數 2140 閱讀 5660

# coding=utf-8

# 深入理解類裝飾器

# 一:類裝飾器(都不帶引數)

class

clsdeco:

def__init__

(self, func):

self.func = func

def__call__

(self, *args, **kwargs):

print(f'running ')

self.func()

print('end')

@clsdeco # 等價於 bar = clsdeco(bar)

defbar

(): print('do something')

# call bar()

# out:

# running bar

# do something

# end

# 二:類裝飾器帶引數

class

clsdeco1:

def__init__

(self, x, y):

self.x = x

self.y = y

def__call__

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

print(f'running ')

print(f'using x + y = ')

return func

@clsdeco1(1,2) # 等價於 bar1 = clsdeco1(1,2)(bar1)

defbar1

(): print('do something')

# call bar1()

# out:

# running bar1

# using x + y = 3

# do something

# 三:類裝飾器不帶引數,被包裝物件帶引數

class

clsdeco2:

def__init__

(self, func):

self.func = func

def__call__

(self, *args, **kwargs):

print(f'running ')

self.func(*args, **kwargs)

print('end')

@clsdeco2 # 等價於bar2 = clsdeco2(bar2)

defbar2

(a,b):

print('do something')

print(f'return a + b = ')

# bar2(1,2)

# out:

# running bar2

# do something

# return a + b = 3

# end

# 四:類裝飾器帶引數且被裝飾物件也帶引數

class

clsdeco3:

def__init__

(self, x, y):

self.x = x

self.y = y

def__call__

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

print(f'using x + y = ')

def(*args, **kwargs):

func(*args, **kwargs)

print('ending')

@clsdeco3(1, 2) # 等價於 bar3 = clsdeco3(1, 2)(bar3)

defbar3

(a, b):

print('do something')

print(f'return a + b = ')

# call bar3(1,2)

# out:

# using x + y = 3

# do something

# return a + b = 3

# ending

if __name__ == '__main__':

bar3(1,2)

python裝飾器理解 python裝飾器理解

裝飾器 在不改變原函式的 和呼叫方法的基礎上,給原函式增加額外的功能 理解宣告 為了方便理解,以下例子採用最簡潔的函式和新增的功能 給原函式新增乙個執行時間 import time def timer func def inner func return inner timer func timer...

python裝飾器 理解Python裝飾器

在python中,對於乙個函式,若想在其執行前後做點什麼,那麼裝飾器是再好不過的選擇,話不多說,上 usr bin env coding utf 8 script 01.py author howie from functools import wraps def decorator func wr...

python裝飾器理解 python裝飾器的理解

python裝飾器應該算是面試常考到的用點,之前在flask的應用中也是會常常用到,抽空仔細看書查資料理解了下裝飾器的概念,通過自己的理解記憶,應該對這個概念會有乙個大致上具體的了解。閉包說起python裝飾器,我們應該不得不談談閉包的概念。我對閉包的理解是,當函式存在巢狀,子函式呼叫了父函式的變數...