程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python | attribute wrapper

編輯:Python

1. Common method

1.1. The decorator has no parameters

def warp(callback):
def f(*args, **kwargs):
print(' Before you call ')
callback(*args, **kwargs)
print(' After call ')
return f
@warp
def hello(name: str = ' Not set '):
print(f'hello {
name}')
if __name__ == '__main__':
hello('yimt')

Output

 Before you call
hello yimt
After call

1.2. Decorators have parameters

def warp(name: str):
def f1(callback):
def f2(*args, **kwargs):
kwargs['name'] = name
print(' Before you call ')
callback(*args, **kwargs)
print(' After call ')
return f2
return f1
@warp('yimt')
def hello(name: str = ' Not set '):
print(f'hello {
name}')
if __name__ == '__main__':
hello()

Output

 Before you call
hello yimt
After call

2. Class method

2.1. Decorator without parameters

def wrap(callback):
def f(*args, **kwargs):
print(' Before you call ')
r = callback(*args, **kwargs)
print(' After call ')
return r
return f
class A:
@wrap
def hello(self, name: str = ' Not set '):
print(f'hello {
name}')
a = A()
a.hello('yimt')

Output

 Before you call
hello yimt
After call

2.2. Decorator with parameters

def wrap(name: str):
def f1(callback):
def f2(*args, **kwargs):
kwargs['name'] = name
print(' Before you call ')
r = callback(*args, **kwargs)
print(' After call ')
return r
return f2
return f1
class A:
@wrap('yimt')
def hello(self, name: str = ' Not set '):
print(f'hello {
name}')
a = A()
a.hello()

Output

 Before you call
hello yimt
After call

3. More ornaments

def warp_a(callback):
def f(*args, **kwargs):
print('a Before you call ')
callback(*args, **kwargs)
print('a After call ')
return f
def warp_b(callback):
def f(*args, **kwargs):
print('b Before you call ')
callback(*args, **kwargs)
print('b After call ')
return f
@warp_a
@warp_b
def hello(name: str = ' Not set '):
print(f'hello {
name}')
if __name__ == '__main__':
hello('yimt')

Output

a Before you call
b Before you call
hello yimt
b After call
a After call

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved