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

2020-12-21 17:33:08 +08:00
 fanqieipnet
如何使用 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.
588 次点击
所在节点    推广
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/737568

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX