源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python使用修饰器执行函数的参数检查功能示例

  • 时间:2021-04-22 19:55 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python使用修饰器执行函数的参数检查功能示例
本文实例讲述了Python使用修饰器执行函数的参数检查功能。分享给大家供大家参考,具体如下: 参数检查:1. 参数的个数;2. 参数的类型;3. 返回值的类型。 考虑如下的函数:
import html
def make_tagged(text, tag):
  return '<{0}>{1}</{0}>'.format(tag, html.escape(text))

显然我们希望传递进来两个参数,且参数类型/返回值类型均为str,再考虑如下的函数:
def repeat(what, count, separator) :
  return ((what + separator)*count)[:-len(separator)]

显然我们希望传递进来三个参数,分别为str,int,str类型,可对返回值不做要求。 那么我们该如何实现对上述参数要求,进行参数检查呢?
import functools
def statically_typed(*types, return_type=None):
  def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
      if len(args) > len(types):
        raise ValueError('too many arguments')
      elif len(args) < len(types):
        raise ValueError('too few arguments')
      for i, (type_, arg) in enumerate(zip(types, args)):
        if not isinstance(type_, arg):
          raise ValueError('argument {} must be of type {}'.format(i, type_.__name__))
      result = func(*args, **kwargs)
      if return_type is not None and not isinstance(result, return_type):
        raise ValueError('return value must be of type {}'.format(return_type.__name__))
      return wrapper
    return decorator

这样,我们便可以使用修饰器模板执行参数检查了:
@statically_typed(str, str, return_type=str)
def make_tagged(text, tag):
  return '<{0}>{1}</{0}>'.format(tag, html.escape(text))
@statically_typed(str, int, str)
def repeat(what, count, separator):
  return ((what + separator)*count)[:-len(separator)]

[b]注:[/b]从静态类型语言(C/C++、Java)转入 Python 的开发者可能比较喜欢用修饰器对函数的参数及返回值执行静态类型检查,但这样做会增加 Python 程序在运行期的开销,而编译型语言则没有这种运行期开销(Python 是解释型语言)。 更多关于Python相关内容可查看本站专题:《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部