设为首页 加入收藏

TOP

python装饰器练习题
2017-09-30 16:58:43 】 浏览:7241
Tags:python 装饰 习题

练习题1. 请使用python, 对下面的函数进行处理,

def hello(name):
    print "hello, %s" % name

在函数被调用时打印耗时详情

<function name: hello>
<function call begin>
hello, tom
<function call end>
[timecosts: 3.81469726562e-06s]

答案:

用到了装饰器,一个很简单的装饰器

贴出代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = '人生入戏'

import time

def calc_time(func):
    def wrapper(*args,**kwargs):
        print("<function name: %s>" % func.__name__)
        print("<function call begin>")
        start_time = time.clock()
        func(*args,**kwargs)
        time.sleep(1)
        end_time = time.clock()
        print("<function call end>")
        print("time costs:%f" % (end_time - start_time))
    return wrapper

@calc_time
def hello(name):
    print("Hello, %s" % name)

hello("World")

运行结果:

<function name: hello>
<function call begin>
hello, world
<function call end>
time costs:0.999846
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇1.开篇 Hello world 下一篇python时间处理

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目