装饰器(Decorators)是 Python 的一个重要部分。
简单地说:
他们是修改其他函数的功能的函数。
他们有助于让我们的代码更简短,也更Pythonic(Python范儿)。
大多数初学者不知道在哪儿使用它们,
所以我将要分享下,
哪些区域里装饰器可以让你的代码更简洁。 首先,让我们讨论下如何写你自己的装饰器。
#! /usr/bin/env python
class decorator():
def before_func_decorator(func):
print("")
def warpTheFunction():
print("I am doing some boring work before executing func")
func()
print("I am doing some boring work after executing func")
return warpTheFunction()
def hi():
return "hi yasoob"
def func_test_decorator():
print("hi I am the function which need decorator")
@decorator.before_func_decorator
def func_with_decorator():
print("test whether I am the function which need decorator")
网友评论