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

如何使用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 TypeEr

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apress 2019出版 Python is one of the most popular languages today. Relatively new fields such as data science, AI, robotics, and data analytics, along with traditional professions such as web development and scientific research, are embracing Python. It’s increasingly important for programmers writing code in a dynamic language like Python to make sure that the code is highquality and error-free. As a Python developer, you want to make sure that the software you are building makes your users happy without going over budget or never releasing. Python is a simple language, yet it’s difficult to write great code because there aren’t many resources that teach how to write better Python code. Currently lacking in the Python world are code consistency, patterns, and an understanding of good Pythonic code among developers. For every Python programmer, great Pythonic code has a different meaning. The reason for this could be that Python is being used in so many areas that it’s difficult to reach consensus among developers about specific patterns. In addition, Python doesn’t have any books about clean code like Java and Ruby do. There have been attempts to write those kinds of books to bring clarity to good Python practices, but those attempts have been few and far between, and quickly frankly, they haven’t been high-quality. The main goal of this book is to provide tips to Python developers of various levels so they can write better Python software and programs. This book gives you various techniques irrespective of the field you use Python in. This book covers all levels of Python, from basic to advanced, and shows you how to make your code more Pythonic. Remember, writing software is not only science but art, and this book will teach you how to become a better Python programmer.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值