侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python 3.7新功能之dataclass装饰器详解

Python  /  管理员 发布于 7年前   348

前言

Python 3.7 将于今年夏天发布,Python 3.7 中将会有许多新东西:

  • 各种字符集的改进
  • 对注释的推迟评估
  • 以及对dataclass的支持

最激动人心的新功能之一是 dataclass 装饰器。

什么是 Data Class

大多数 Python 开发人员编写过很多像下面这样的类:

class MyClass: def __init__(self, var_a, var_b): self.var_a = var_a self.var_b = var_b

dataclass 可以为简单的情况自动生成方法,例如,一个__init__接受这些参数并将其分配给自己,之前的小例子可以重写为:

@dataclassclass MyClass: var_a: str var_b: str

那么通过一个例子来看看如何使用吧

星球大战 API

可以使用 requests 从星球大战 API 获取资源:

response = requests.get('https://swapi.co/api/films/1/')dictionary = response.json()

让我们来看看 dictionary (简化过)的结果:

{ 'characters': ['https://swapi.co/api/people/1/',… ], 'created': '2014-12-10T14:23:31.880000Z', 'director': 'George Lucas', 'edited': '2015-04-11T09:46:52.774897Z', 'episode_id': 4, 'opening_crawl': 'It is a period of civil war.\r\n … ', 'planets': ['https://swapi.co/api/planets/2/', … ], 'producer': 'Gary Kurtz, Rick McCallum', 'release_date': '1977-05-25', 'species': ['https://swapi.co/api/species/5/',…], 'starships': ['https://swapi.co/api/starships/2/',…], 'title': 'A New Hope', 'url': 'https://swapi.co/api/films/1/', 'vehicles': ['https://swapi.co/api/vehicles/4/',…]

封装 API

为了正确地封装一个 API,我们应该创建一个用户可以在其应用程序中使用的对象,因此,在Python 3.6 中定义一个对象来包含requests对 /films/endpoint的响应:

class StarWarsMovie: def __init__(self,   title: str,   episode_id: int,   opening_crawl: str,   director: str,   producer: str,   release_date: datetime,   characters: List[str],   planets: List[str],   starships: List[str],   vehicles: List[str],   species: List[str],   created: datetime,   edited: datetime,   url: str   ): self.title = title self.episode_id = episode_id self.opening_crawl= opening_crawl self.director = director self.producer = producer self.release_date = release_date self.characters = characters self.planets = planets self.starships = starships self.vehicles = vehicles self.species = species self.created = created self.edited = edited self.url = url if type(self.release_date) is str:  self.release_date = dateutil.parser.parse(self.release_date) if type(self.created) is str:  self.created = dateutil.parser.parse(self.created) if type(self.edited) is str:  self.edited = dateutil.parser.parse(self.edited)

仔细的读者可能已经注意到这里有一些重复的代码。

这是使用 dataclass 装饰器的经典案例,我们需要创建一个主要用来保存数据的类,只需一点验证,所以让我们来看看我们需要修改什么。

首先,data class 自动生成一些 dunder 方法,如果我们没有为 data class 装饰器指定任何选项,则生成的方法有:__init__,__eq__和__repr__,如果你已经定义了__repr__但没定义__str__,默认情况下 Python(不仅仅是 data class)将实现返回__repr__的输出__str__方法。因此,只需将代码更改为以下代码即可实现四种 dunder 方法:

@dataclassclass StarWarsMovie: title: str episode_id: int opening_crawl: str director: str producer: str release_date: datetime characters: List[str] planets: List[str] starships: List[str] vehicles: List[str] species: List[str] created: datetime edited: datetime url: str

我们去掉了__init__方法,以确保 data class 装饰器可以添加它生成的对应方法。不过,我们在这个过程中失去了一些功能,我们的 Python 3.6 构造函数不仅定义了所有的值,还试图解析日期,我们怎样才能用 data class 来做到这一点呢?

如果要覆盖 __init__,我们将失去 data class 的优势,因此,如果要处理任何附加功能可以使用新的 dunder 方法:__post_init__,让我们看看__post_init__方法对于我们的包装类来说是什么样子的:

def __post_init__(self): if type(self.release_date) is str:  self.release_date = dateutil.parser.parse(self.release_date) if type(self.created) is str:  self.created = dateutil.parser.parse(self.created) if type(self.edited) is str:  self.edited = dateutil.parser.parse(self.edited)

就是这样! 我们可以使用 data class 装饰器在用三分之二的代码量实现我们的类。

更多好东西

通过使用装饰器的选项,可以为用例进一步定制 data class,默认选项是:

@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
  • init决定是否生成__init__ dunder 方法
  • repr决定是否生成__repr__ dunder方法
  • eq对__eq__ dunder 方法也是如此,它决定相等性检查的行为(your_class_instance == another_instance)
  • order 实际上创建了四种 dunder 方法,它们确定所有检查小于,and/or,大于的行为,如果将其设置为 true,则可以对对象列表进行排序。

最后两个选项确定对象是否可以被哈希化,如果你想使用你的 class 的对象作为字典键的话,这是必要的。

更多信息请参考:PEP 557 -- Data Classes

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家的支持。


  • 上一条:
    使用Python和xlwt向Excel文件中写入中文的实例
    下一条:
    Python使用pip安装pySerial串口通讯模块
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客