Discuss / Python / 资源推荐

资源推荐

Topic source

作者装饰器写的对入门者有难度,建议看一下这个视频,一看就全动了:1. python装饰器:第一回合_哔哩哔哩_bilibili

Valeera

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

感谢推荐

确实很不错,感谢!

行云流水

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

看完这个视频,就清楚多了,多谢推荐。

下面讲讲我的感受

老师文中给出两个例子

#例子1
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
        
    return wrapper

@log
def now():
     print('2015-3-25')

print(now.__name__)  #结果是 wrapper

#例子2
def log(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator

@log('excute')
def now():
     print('2015-3-25')

print(now.__name__)  #结果都是 wrapper

直接的 @log 时,python将下面定义的函数作为参数传入log的括号中,now = log**(now)**

log(now)因为带一对括号,函数会执行一次(这个是视频里比较强调的一点,老师也有提,但是文字记忆不太深刻,看了视频我才注意到)

所以例子1 是 @log  默认执行一次后返回使用参数(now)后的 wrapper函数,所以 .__name__  是wrapper

例子2 是 @log('excute'),一对括号加默认的括号,所以执行两次,返回的还是wrapper。

然后是作业

#打印时间

import time, functools

def metric(fn):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        res = fn(*args, **kwargs)
        print('%s executed in %s ms' % (fn.__name__, time.time()-start_time))
        return res

    return wrapper

# 测试
@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;

f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
    print('测试失败!')
elif s != 7986:
    print('测试失败!')

思考题

import time, functools

def log(*args):
    def decorator(func):
        # @functools.wraps(func)
        def wrapper(*args, **kwargs):
            print('begin call')
            res = func(*args, **kwargs)
            print('end call')
            return res

        return wrapper

    return decorator

#测试
@log() #不加括号会报错
def f():
    pass
    print('call function done')
    return 'all finished'

print(f())

print('\n')

@log('execute')
def g():
    pass
    print('call function done')
    return 'all finished'

print(g())

有梦不难

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

我按照行云流水的方法做的,为什么会出现两次fast

fast executed in 0.022995471954345703 ms

fast executed in 0.022995471954345703 ms

slow executed in 0.12615680694580078 ms

Process finished with exit code 0

zeal_z

#6 Created at ... [Delete] [Delete and Lock User]
@log('execute')
def g():
    pass
    print('call function done')
    return 'all finished'
g()这样写是不是体现不出‘execute’这个参数

感谢,看完终于理解了

Geek_韧

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

感谢推荐

yan32777

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

这个老师讲的太细了,对熟悉过基础语言的人来说,大没必要。


  • 1

Reply