<jupyter_start><jupyter_text>装饰器会丢掉原函数的信息<jupyter_code>function_1.__name__
function_1.__doc__<jupyter_output><empty_output><jupyter_text>解决方法<jupyter_code>from functools import wraps
def cal_time(f):
    @wraps(f)
    def inner(*args, **kargs):
        start_time = datetime.now()
        result = f(*args, **kargs)
        end_time = datetime.now()
        print('使用了{}秒'.format((end_time - start_time).total_seconds()))
        
        return result
    
    return inner
        
@cal_time
def function_3(a, b):
    '''除法'''
    return a / b
function_3.__name__
function_3.__doc__<jupyter_output><empty_output><jupyter_text>带参数的装饰器  ```cal_time本身不是装饰器，而是返回了一个装饰器<jupyter_code>def cal_time(unit='s'):
    def decorator(f):
        def inner(*args, **kargs):
            start_time = datetime.now()
            result = f(*args, **kargs)
            end_time = datetime.now()
            if unit=='s':
                print('使用了{}秒'.format((end_time - start_time).total_seconds()))
            elif unit == 'm':
                print('使用了{}分钟'.format((end_time - start_time).total_seconds()/60))
            else:
                raise ValueError('Unknown Erro')

            return result    
        return inner
    return decorator<jupyter_output><empty_output><jupyter_text>注意用法，```cal_time```这里需要调用, 而装饰器本身不需要调用<jupyter_code>@cal_time(unit='s')
def function_2():
    '''等3秒'''
    time.sleep(3)

function_2()
@cal_time(unit='m')
def function_2():
    '''等3秒'''
    time.sleep(3)
function_2()<jupyter_output>使用了0.050033466666666665分钟<jupyter_text>装饰器可以用在method上<jupyter_code>class T:
    @cal_time(unit='m')
    def wait(self, t):
        time.sleep(t)
t = T()

t.wait(1)<jupyter_output>使用了0.016754583333333333分钟<jupyter_text>method的```function用法```<jupyter_code>T.wait(t, 1)<jupyter_output>使用了0.0167436分钟
{'fraction_non_alphanumeric': 0.14624724061810154, 'fraction_numerical': 0.0347682119205298, 'mean_word_length': 3.4545454545454546, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '225647', 'license': 'MIT', 'n_tokens_mistral': 761, 'n_tokens_neox': 749, 'n_words': 89, 'path': '0006_closure_and_decorators/decorators.ipynb', 'repo_name': 'junjiecai/jupyter_demos', 'size': '1812'}