python3.7新功能_Python 2.7终结于7个月后,这是你需要了解的3.X炫酷新特性

43a7d933c895d1438aa8eb3fc2285b065baf0728.jpeg?token=161c02a398059de2be8234e10058ef33&s=68FBAB4603F1ABD20EED4D090100B081

从 3.0 到 3.8,Python 3 已经更新了一波又一波,但似乎我们用起来和 2.7 没有太大区别?以前该怎么写 2.7 的代码现在就怎么写,只不过少数表达方式变了而已。在这篇文章中,作者介绍了 3.0 以来真正 Amazing 的新函数与新方法,也许这些方法我们都不太熟,但它们确实在实践中非常重要。

许多人在了解到 Python 2.7 即将停止维护后,都开始将他们的 Python 版本从 2 切换到 3。截止到 5 月 19 号上午 10 点,Python 2.7 将终结于...

c2cec3fdfc039245eaf5d322364c7dc67c1e25b3.jpeg?token=6584b983e1e51c680c3dbdee92d6404f&s=E5B6E77EC574FF221075D06B0200C076

在这一段时间中,很多优秀开源项目与库已经停止了对 2.7 的支持。例如到今年 1 月份,NumPy 将停止支持 Python 2;到今年年末,Ipython、Cython 和 Pandas 等等都将陆续停止支持 Python 2。

虽然我们都往 3.X 迁移,但许多人编写的 Python 3 代码仍然看起来像 Python 2 一样,只不过加入了一些括号或改了些 API。在本文中,作者将展示一些令人激动的 Python 3.X 新特性。这些特性或方法都是 Python 3 各个版本中新加的,它们相比传统的 Python 方法,更容易解决实践中的一些问题。

所有的示例都是在 Python 3.7 的环境下编写的,每个特性示例都给出了其正常工作所需的最低的 Python 版本。

格式化字符串 f-string(最低 Python 版本为 3.6)

在任何的编程语言中,不使用字符串都是寸步难行的。而为了保持思路清晰,你会希望有一种结构化的方法来处理字符串。大多数使用 Python 的人会偏向于使用「format」方法。

user = "Jane Doe"action = "buy"log_message = 'User {} has logged in and did an action {}.'.format( user, action)print(log_message)# User Jane Doe has logged in and did an action buy.

除了「format」,Python 3 还提供了一种通过「f-string」进行字符串插入的灵活方法。使用「f-string」编写的与上面功能相同的代码是这样的:

user = "Jane Doe"action = "buy"log_message = f'User {user} has logged in and did an action {action}.'print(log_message)# User Jane Doe has logged in and did an action buy.

相比于常见的字符串格式符 %s 或 format 方法,f-strings 直接在占位符中插入变量显得更加方便,也更好理解。

路径管理库 Pathlib(最低 Python 版本为 3.4)

f-string 非常强大,但是有些像文件路径这样的字符串有他们自己的库,这些库使得对它们的操作更加容易。Python 3 提供了一种处理文件路径的抽象库「pathlib」。如果你不知道为什么应该使用 pathlib,请参阅下面这篇 Trey Hunner 编写的炒鸡棒的博文:「https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/」

from pathlib import Pathroot = Path('post_sub_folder')print(root)# post_sub_folderpath = root / 'happy_user'# Make the path absoluteprint(path.resolve())# /home/weenkus/Workspace/Projects/DataWhatNow-Codes/how_your_python3_should_look_like/post_sub_folder/happy_user

如上所示,我们可以直接对路径的字符串进行「/」操作,并在绝对与相对地址间做转换。

类型提示 Type hinting(最低 Python 版本为 3.5)

静态和动态类型是软件工程中一个热门的话题,几乎每个人 对此有自己的看法。读者应该自己决定何时应该编写何种类型,因此你至少需要知道 Python 3 是支持类型提示的。

defsentence_has_animal(sentence: str) -> bool:return"animal"in sentencesentence_has_animal("Donald had a farm without animals")# True

枚举(最低 Python 版本为 3.4)

Python 3 支持通过「Enum」类编写枚举的简单方法。枚举是一种封装常量列表的便捷方法,因此这些列表不会在结构性不强的情况下随机分布在代码中。

from enum import Enum, autoclassMonster(Enum): ZOMBIE = auto() WARRIOR = auto() BEAR = auto()print(Monster.ZOMBIE)# Monster.ZOMBIE

枚举是符号名称(成员)的集合,这些符号名称与唯一的常量值绑定在一起。在枚举中,可以通过标识对成员进行比较操作,枚举本身也可以被遍历。

参考:https://docs.python.org/3/library/enum.html

for monster in Monster: print(monster)# Monster.ZOMBIE# Monster.WARRIOR# Monster.BEAR

原生 LRU 缓存(最低 Python 版本为 3.2)

目前,几乎所有层面上的软件和硬件中都需要缓存。Python 3 将 LRU(最近最少使用算法)缓存作为一个名为「lru_cache」的装饰器,使得对缓存的使用非常简单。

下面是一个简单的斐波那契函数,我们知道使用缓存将有助于该函数的计算,因为它会通过递归多次执行相同的工作。

import timedeffib(number: int) -> int:if number == 0: return0if number == 1: return1return fib(number-1) + fib(number-2)start = time.time()fib(40)print(f'Duration: {time.time() - start}s')# Duration: 30.684099674224854s

现在,我们可以使用「lru_cache」来优化它(这种优化技术被称为「memoization」)。通过这种优化,我们将执行时间从几秒降低到了几纳秒。

from functools import lru_cache@lru_cache(maxsize=512)deffib_memoization(number: int) -> int:if number == 0: return0if number == 1: return1return fib_memoization(number-1) + fib_memoization(number-2)start = time.time()fib_memoization(40)print(f'Duration: {time.time() - start}s')# Duration: 6.866455078125e-05s

扩展的可迭代对象解包(最低 Python 版本为 3.0)

对于这个特性,代码就说明了一切。

参考:https://www.python.org/dev/peps/pep-3132/

head, *body, tail = range(5)print(head, body, tail)# 0 [1, 2, 3] 4py, filename, *cmds = "python3.7 script.py -n 5 -l 15".split()print(py)print(filename)print(cmds)# python3.7# script.py# ['-n', '5', '-l', '15']first, _, third, *_ = range(10)print(first, third)# 0 2

Data class 装饰器(最低 Python 版本为 3.7)

Python 3 引入了「data class」,它们没有太多的限制,可以用来减少对样板代码的使用,因为装饰器会自动生成诸如「__init__()」和「__repr()__」这样的特殊方法。在官方的文档中,它们被描述为「带有缺省值的可变命名元组」。

classArmor:def__init__(self, armor: float, description: str, level: int = 1): self.armor = armor self.level = level self.description = descriptiondefpower(self) -> float:return self.armor * self.levelarmor = Armor(5.2, "Common armor.", 2)armor.power()# 10.4print(armor)# <__main__.Armor object at 0x7fc4800e2cf8>

使用「Data class」实现相同的 Armor 类。

from dataclasses import dataclass@dataclassclassArmor: armor: float description: str level: int = 1defpower(self) -> float:return self.armor * self.levelarmor = Armor(5.2, "Common armor.", 2)armor.power()# 10.4print(armor)# Armor(armor=5.2, description='Common armor.', level=2)

隐式命名空间包(最低 Python 版本为 3.3)

一种组织 Python 代码文件的方式是将它们封装在程序包中(包含一个「__init__.py」的文件夹)。下面是官方文档提供的示例。

sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ...

在 Python 2 中,上面每个文件夹都必须包含将文件夹转化为 Python 程序包的「__init__.py」文件。在 Python 3 中,随着隐式命名空间包的引入,这些文件不再是必须的了。

sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects echo.py surround.py reverse.py ... filters/ Subpackage for filters equalizer.py vocoder.py karaoke.py ...

正如有些人说的那样,这项工作并没有像这篇文章说的那么简单,官方文档「PEP 420 Specification」指出,常规的程序包仍然需要「__init__.py」,把它从一个文件夹中删除会将该文件夹变成一个本地命名空间包,这会带来一些额外的限制。本地命名空间包的官方文档给出了一个很好的示例,并且明确指出了所有的限制。

结语

和网上几乎所有的技术列表一样,本文给出的列表也并不完整。希望这篇文章至少向你展示了一些以前不知道的 Python 3 功能,它将帮助你编写出更加干净、 直观的代码。

最后,本文中给出的所有代码都可以在作者的 GitHub 上找到:https://github.com/Weenkus/DataWhatNow-Codes/blob/master/things_you_are_probably_not_using_in_python_3_but_should/python%203%20examples.ipynb

原文链接:https://datawhatnow.com/things-you-are-probably-not-using-in-python-3-but-should/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值