# 装饰器

### 待参数类实现的装饰器

```python
'''
以类实现待参数的装饰器

1. wrap_logger() 立刻对应 __init__
2. obj(func) 立刻对应 __call__
3. func = callable(func), 第一对象callable，开始执行，
   并且内部有定义了一个函数 wrapper，并返回(和定义了一个变量wrapper并返回没有区别)
    @callable
    def func():
       pass
4. 区分不同部分含义
 - 装饰器定义部分
 - 加装饰器业务函数定义部分
 - 业务函数执行部分
'''

import uuid
import functools


# 装饰器定义部分
class wrap_logger(object):
    def __init__(self, logger, prefix, no_generator=None):
        super(wrap_logger, self).__init__()
        self.logger = logger
        self.prefix = prefix
        if not no_generator:
            no_generator = uuid.uuid1
        self.no_generator = no_generator

    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*arg, **kw):
            no = str(self.no_generator())
            self.logger.warning(self.prefix + ' start %s' % no)
            try:
                return func(*arg, **kw)
            except Exception as e:
                raise e
            finally:
                self.logger.warning(self.prefix + ' end %s' % no)
        return wrapper


import logging
import time
log = logging.getLogger(__name__)

# 加装饰器业务函数定义部分
@wrap_logger(log, 'func', no_generator=time.time)
def func(name):
    time.sleep(3)
    print('from func name: %s' % name)


# 业务函数执行部分
func('linda')
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nining.website/python/func/decorator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
