zoukankan      html  css  js  c++  java
  • Python_如何定义带参数的装饰器?

    案例:

           实现一个装饰器,用它来检查被装饰函数的参数类型。

           需求:

        装饰器可以通过函数,指明函数参数类型,进行函数调用的时候,传入参数,检测到不匹配时,抛出异常

    如何解决这个问题?

    1. 先要获取函数的签名,并且获得装饰器中参数,然后把函数签名和装饰器中参数对应绑定
    2. 把调用函数时候传入的参数和函数签名进行绑定
    3. 把实参和装饰器中定义的数据进行类型比较,不匹配抛出异常
      #!/usr/bin/python3
      
      from inspect import signature
      
      
      def check_type(*ty_args, **ty_kwargs):
          
          def out_wrapper(func):
              # 通过signature方法,获取函数形参:name, age, height
              sig = signature(func)
              # 获得装饰器传来的参数, 函数签名与之绑定,字典类型
              bind_types = sig.bind_partial(*ty_args, **ty_kwargs).arguments
              print(bind_types)
              
              def wrapper(*args, **kwargs):
                  # 给执行函数中具体的实参进行和形参进行绑定,形成字典的形式
                  func_type = sig.bind(*args, **kwargs).arguments.items()
                  print(func_type)
                  # 循环形参和实参字典的items()形式
                  for name, obj in func_type:
                      if name in bind_types:
                          if not isinstance(obj, bind_types[name]):
                              raise TypeError('%s must be %s' % (name, bind_types[name]))
                  func(*args, **kwargs)
              return wrapper
          return out_wrapper
      
      
      # 通过装饰器实现对函数参数进行类型检查
      @check_type(str, int, float)
      def func(name, age, height):
          print(name, age, height)
      
      
      if __name__ == '__main__':
          func('bei_men', 18, 1.75)
      

        

  • 相关阅读:
    python三大神器之virtualenv pip, virtualenv, fabric通称为pythoner的三大神器。
    pip使用国内镜像,豆瓣、清华
    pip国内源
    Android原生(Native)C开发之四:SDL移植笔记
    libcurl使用easy模式阻塞卡死等问题的完美解决
    linux 自定义信号
    ubuntu 12.04安装telnet和ssh服务
    libcurl with telnet
    ubuntu使用ssh登入不执行.bashrc解决方法
    pthread_kill
  • 原文地址:https://www.cnblogs.com/2bjiujiu/p/7291819.html
Copyright © 2011-2022 走看看