极简样式:
# Define a decorator
def outter(func):
def alternative():
# ...Some code here...
result = func()
# ...Some code here...
return result
return alternative
# Apply a decorator
@outter
def stable_method():
pass
标准样式:
# Define a decorator
def outter(func):
def alternative(*args, **kargs):
# ...Some code here...
result = func(*args, **kargs)
# ...Some code here...
return result
return alternative
# Apply a decorator
@outter
def stable_method():
pass
装饰器带参数样式:
# Define a decorator
def outter(name):
def inner(func):
def alternative(*args, **kargs):
print('I can use name={} here'.format(name))
# ...Some code here...
result = func(*args, **kargs)
# ...Some code here...
return result
return alternative
return inner
# Apply a decorator
@outter(name='Jason')
def stable_method():
pass
``
## 类中定义装饰器
[参考:Decorator inside Python class](https://medium.com/@vadimpushtaev/decorator-inside-python-class-1e74d23107f6)
网友评论