栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

保留装饰功能的签名

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

保留装饰功能的签名

  1. 安装装饰器模块:

    $ pip install decorator
  2. 修改以下内容的定义

    args_as_ints()

    import decorator

    @decorator.decorator
    def args_as_ints(f, args, kwargs):
    args = [int(x) for x in args]
    kwargs = dict((k, int(v)) for k, v in kwargs.items())
    return f(
    args, **kwargs)

    @args_as_ints
    def funny_function(x, y, z=3):
    “”“Computes xy + 2z”“”
    return xy + 2z

    print funny_function(“3”, 4.0, z=”5”)

    22

    help(funny_function)

    Help on function funny_function in module main:

    funny_function(x, y, z=3)

    Computes xy + 2z


Python 3.4以上

functools.wraps()
自Python
3.4起,来自stdlib的文件就保留了签名:

import functoolsdef args_as_ints(func):    @functools.wraps(func)    def wrapper(*args, **kwargs):        args = [int(x) for x in args]        kwargs = dict((k, int(v)) for k, v in kwargs.items())        return func(*args, **kwargs)    return wrapper@args_as_intsdef funny_function(x, y, z=3):    """Computes x*y + 2*z"""    return x*y + 2*zprint(funny_function("3", 4.0, z="5"))# 22help(funny_function)# Help on function funny_function in module __main__:## funny_function(x, y, z=3)#     Computes x*y + 2*z

functools.wraps()
至少从Python 2.5开始就可用,但是它不在那里保留签名:

help(funny_function)# Help on function funny_function in module __main__:## funny_function(*args, **kwargs)#    Computes x*y + 2*z

注意:

*args, **kwargs
代替
x, y, z=3



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516791.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号