python面试题

python装饰器

装饰器的本质就是一个函数能为其它函数增加额外功能

装饰器不加参数

python 复制代码
#coding:utf-8
from time import time

#装饰器函数
def elapsed(target):
    "统计目标函数执行的耗时"
    def decorated(*args,**kwargs):
        start = time()
        r = target(*args,**kwargs)
        end = time()
        print("函数执行的耗时:",end - start)
        return r
    return decorated

#对目标函数进行elapsed装饰器函数的调用
#返回一个装饰后的名字还是叫power_sum的函数
@elapsed
def power_sum(n):
    total = 0
    for i in range(1,n+1):
        total += i ** 2
    return total
if __name__ == '__main__':
    #调用装饰器函数,装饰目标函数,得到一个装饰后的函数
    # power_sum = elapsed(power_sum)
    # print(power_sum(100000))
    #加上python的装饰器后
    print(power_sum(100000))

装饰器加上参数

python 复制代码
#coding:utf-8
from time import time

#装饰器函数
def elapsed_precision(n):
    def elapsed(target):
        "统计目标函数执行的耗时"
        def decorated(*args,**kwargs):
            start = time()
            r = target(*args,**kwargs)
            end = time()
            print("函数执行的耗时:",round(end - start,n))
            return r
        return decorated
    return elapsed

#对目标函数进行elapsed装饰器函数的调用
#返回一个装饰后的名字还是叫power_sum的函数
@elapsed_precision(2)
def power_sum(n):
    total = 0
    for i in range(1,n+1):
        total += i ** 2
    return total
if __name__ == '__main__':
    #调用装饰器函数,装饰目标函数,得到一个装饰后的函数
    # power_sum = elapsed(power_sum)
    # print(power_sum(100000))
    #加上python的装饰器后
    print(power_sum(100000))
相关推荐
久绊A1 小时前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J4 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶4 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
失败尽常态5237 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447747 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农7 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿7 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing8 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
xinxiyinhe9 小时前
如何设置Cursor中.cursorrules文件
人工智能·python
诸神缄默不语9 小时前
如何用Python 3自动打开exe程序
python·os·subprocess·python 3