V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
如果想在 V2EX 获得更好的推广效果,欢迎了解 PRO 会员机制:
https://www.v2ex.com/pro/about
fanqieipnet
V2EX  ›  推广

如何使用 Python 类装饰器,实现代码 clean

  •  
  •   fanqieipnet · Dec 21, 2020 · 917 views
    This topic created in 1961 days ago, the information mentioned may be changed or developed.
    如何使用 Python 类装饰器,实现代码 clean?今天番茄加速就来给大家讲解一下。

      实现同样一个功能,用 Java 语言可能得 50 行,而用 Python 可能只需 10 行,可能很多读者在没有学 Python 前,就从用过 Python 的前辈那里,听说过这个,然后自己也开始去学 Python 的。

       Python 的确简洁、优雅,很多读者包括我,都为之着迷。

      今天通过一个小例子,再次认识 Python 的 clean 之道:

      我们想要检查每个参数,确保不能出现整数类型。使用类装饰器,便能做到 clean,通用:

       import functools

       class ValidateParameters:

       def __init__(self, func):

      # 确保 func 被装饰后函数信息不被改变

       functools.update_wrapper(self, func)

       self.func = func

      # 重写此方法,让类对象变得可调用

       def __call__(self, *parameters):

       if any([isinstance(item, int) for item in parameters]):

       raise TypeError("Parameter shouldn't be int!!")

       else:

       return self.func(*parameters)

      使用上面的类,开始装饰我们的各种函数,比如连接字符串函数 concat,第一次调用传参都为字符串,类型满足要求;第二次调用传参有整数类型,抛出异常:Parameter shouldn't be int!!

       @ValidateParameters

       def concat(*list_string):

       return "".join(list_string)

      # returns anb

       print(concat("a", "n", "b"))

      # raises Error.

       print(concat("a", 1, "c"))

      任意一个想要有类型检查的函数,都可以装饰上 ValidateParemeters,如下 capital 函数,实现串联字符串后,且首字母大写:

       @ValidateParameters

       def capital(*list_string):

       return concat(*list_string).capitalize()

       print(capital("a", "n", "b"))

       print(capital(2, "n", "b"))

      如果输入参数有整型,必然抛出上面的异常,再次方便的实现类型检查。

      以上使用 Python 类装饰器,实现代码 clean 的一个小演示。

      常用的如 Pandas 、TensorFlow 、Keras 等框架,里面的源码,都能看到类似用法,这类语法让 Python 真正做到 clean.
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   787 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 20:19 · PVG 04:19 · LAX 13:19 · JFK 16:19
    ♥ Do have faith in what you're doing.