Discuss / Python / 作业8 装饰器练习

作业8 装饰器练习

Topic source

孤o赦免你

#1 Created at ... [Delete] [Delete and Lock User]

import functools

import time

# decorator练习1

def metric(func):

    def swapper(*args, **kwargs):

        t1 = time.time()

        f = func(*args, **kwargs)

        t2 = time.time()

        print('%s runtime is: %s' % (func.__name__, t2 - t1))

        return f

    return swapper

# decorator练习2

def log(text):

    def decorator(func):

        @functools.wraps(func)

        def swapper(*args, **kwargs):

            print('begin cell %s():' % text)

            f = func(*args, **kwargs)

            print('end cell %s()' % text)

            return f

        return swapper

    return decorator

@metric

def fast(x, y):

    time.sleep(0.0012)

    return x + y

@metric

def slow(x, y, z):

    time.sleep(0.1234)

    return x * y * z

@log('test')

def log_test(x, y):

    print('x + y =', x + y)

f = fast(11, 22)

print(f)

s = slow(11, 22, 33)

print(s)

if f != 33:

    print('测试失败!')

elif s != 7986:

    print('测试失败!')

log_test(7, 8)


  • 1

Reply