你不得不了解的Python3.x新特性
从 3.0 到 3.8,Python 3 已经更新了一波又一波,但似乎我们用起来和 2.7 没有太大区别?以前该怎么写 2.7 的代码现在就怎么写,只不过少数表达方式变了而已。在这篇文章中,作者介绍了 3.0 以来真正 Amazing 的新函数与新方法,也许这些方法我们都不太熟,但它们确实在实践中非常重要。
一、格式化字符串f-string
在任何的编程语言中,不使用字符串都是寸步难行的。而为了保持思路清晰,你会希望有一种结构化的方法来处理字符串。Python中格式化字符串目前有四种方法,大家可以参见我的这篇博客:https://www.cnblogs.com/zhangyafei/p/9837602.html
大多数使用 Python 的人会偏向于使用「format」方法。
# 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」编写的与上面功能相同的代码是这样的:
# 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 Path
root = Path('post_sub_folder')
print(root)
# post_sub_folder
path = root / 'happy_user'
# Make the path absolute
print(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 是支持类型提示的。
def sentence_has_animal(sentence: str) -> bool:
return "animal" in sentence sentence_has_animal("Donald had a farm without animals")
# True
四、枚举(最低 Python 版本为 3.4)
Python 3 支持通过「Enum」类编写枚举的简单方法。枚举是一种封装常量列表的便捷方法,因此这些列表不会在结构性不强的情况下随机分布在代码中。
from enum import Enum, auto class Monster(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 time def fib(number: int) -> int:
if number == 0: return 0
if number == 1: return 1 return fib(number-1) + fib(number-2) start = time.time()
fib(40)
print(f'Duration: {time.time() - start}s')
# Duration: 59.59635329246521s
现在,我们可以使用「lru_cache」来优化它(这种优化技术被称为「memoization」)。通过这种优化,我们将执行时间从几十秒降低到了几纳秒。
from functools import lru_cache @lru_cache(maxsize=512)
def fib_memoization(number: int) -> int:
if number == 0: return 0
if number == 1: return 1 return fib_memoization(number-1) + fib_memoization(number-2) start = time.time()
fib_memoization(40)
print(f'Duration: {time.time() - start}s')
# Duration: 0.0s
六、扩展的可迭代对象解包(最低 Python 版本为 3.0)
对于这个特性,代码就说明了一切。
参考:https://www.python.org/dev/peps/pep-3132/
head, *body, tail = range(5)
print(head, body, tail)
# 0 [1, 2, 3] 4 py, 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()__」这样的特殊方法。在官方的文档中,它们被描述为「带有缺省值的可变命名元组」。
class Armor:
def __init__(self, armor: float, description: str, level: int = 1):
self.armor = armor
self.level = level
self.description = description
def power(self) -> float:
return self.armor * self.level
armor = Armor(5.2, "Common armor.", 2)
armor.power()
# 10.4
print(armor)
# <__main__.Armor object at 0x7fc4800e2cf8>
使用「Data class」实现相同的 Armor 类。
from dataclasses import dataclass @dataclass
class Armor:
armor: float
description: str
level: int = 1 def power(self) -> float:
return self.armor * self.level armor = Armor(5.2, "Common armor.", 2)
result = armor.power() print(armor)
print(result) # Armor(armor=5.2, description='Common armor.', level=2)
# 10.4
你不得不了解的Python3.x新特性的更多相关文章
- 字符串格式的方法%s、format和python3.6新特性f-string和类型注解
一.%s msg = '我叫%s,今年%s,性别%s' %('帅哥',18,'男') print(msg) # 我叫帅哥,今年18,性别男 二.format # 三种方式: # 第一种:按顺序接收参数 ...
- python3.8 新特性
https://docs.python.org/3.8/whatsnew/3.8.html python 3.8的新功能本文解释了与3.7相比,python 3.8中的新特性. 有关完整的详细信息,请 ...
- Python3.8新特性--PositionalOnly参数
“理论联系实惠,密切联系领导,表扬和自我表扬”——我就是老司机,曾经写文章教各位怎么打拼职场的老司机. 不记得没关系,只需要知道:有这么一位老司机, 穿上西装带大家打拼职场! 操起键盘带大家打磨技术! ...
- python3.6 新特性学习
#支持类型提示 typing { def greeting(name: str) -> str: return 'Hello ' + name #在函数greeting中,参数名称的类型为str ...
- python3.8新特性
海象运算符(赋值运算符) #原来 def choice(): s = ' jsadlk '.strip() res = isinstance(s, int) if res: return 'int' ...
- Python3.8新特性-- 海象操作符
“理论联系实惠,密切联系领导,表扬和自我表扬”——我就是老司机,曾经写文章教各位怎么打拼职场的老司机. 不记得没关系,只需要知道:有这么一位老司机, 穿上西装带大家打拼职场! 操起键盘带大家打磨技术! ...
- Python3.X新特性之print和exec
print print 现在是一个函数,不再是一个语句.<语法更为清晰> 实例1 打开文件 log.txt 以便进行写入并将对象指定给 fid.然后利用 print将一个字符串重定向给文件 ...
- python3.6新特性
print(f'{6:^30}') print('\n'.join([' '.join([f'{i}*{j}={i*j:2d}' for j in range(1,i+1)]) for i in ra ...
- Atitit python3.0 3.3 3.5 3.6 新特性 Python2.7新特性1Python 3_x 新特性1python3.4新特性1python3.5新特性1值得关注的新特性1Pyth
Atitit python3.0 3.3 3.5 3.6 新特性 Python2.7新特性1 Python 3_x 新特性1 python3.4新特性1 python3.5新特性1 值得关注的新特性1 ...
随机推荐
- C# 使用管理员权限运行程序
最近在开发OPCServer组件过程中,在注册opcServer是总是返回false,后来查找原因得知在本地主机注册opcServer时,需要使用管理员权限. OPCServer在一台机器上部署时只需 ...
- 12月第二周bug总结
1.bug总结 复制 别人的依赖和依赖指定类型 报错 解决:依赖还没加载完成,你就指定了版本型号,所以报错,所以先让他加载依赖,后指定该型号 eureka(优瑞卡) 注册服务 控制台没有显示出来的话 ...
- Oracle命名规则
1.长度不能超过三十个字符 2. 不要使用Oracle关键字 比如:id name table 3. 不能使用数字开头 包含:数字 字母 下划线 美元符号 4. 建议用 英文单词,不要去用中 ...
- VUE3 之 template 语法
1. 概述 老话说的好:干一行,爱一行,踏实工作才是真正快乐的源泉. 言归正传,今天继续聊 VUE3 的话题,今天聊聊 template 语法. 闲话不多说,直接上代码. 2. template 语法 ...
- 安装Redis5.0.8教程图解
文档:安装Redis5.0.8教程图解.note 链接:http://note.youdao.com/noteshare?id=737620a0441724783c3f8ef14ab8a453& ...
- Xpath 使用技巧
使用xpath 简介 常见语法 选取节点 谓语 通配符 选取多个路径 运算符 其他用法 使用contains选取包含属性 使用tostring()将对象转换为字符串 使用starts-with 使用n ...
- 测试开发实战[提测平台]17-Flask&Vue文件上传实现
微信搜索[大奇测试开],关注这个坚持分享测试开发干货的家伙. 先回顾下在此系列第8次分享给出的预期实现的产品原型和需求说明,如下图整体上和前两节实现很相似,只不过一般测试报告要写的内容可能比较多,就多 ...
- CF570A Elections 题解
Content 有 \(n\) 个候选人和 \(m\) 个城市,每个城市可以给每个候选人投票,已知第 \(i\) 个城市给第 \(j\) 个人投的选票数是 \(a_{i,j}\).我们将第 \(i\) ...
- 【LeetCode】731. My Calendar II 解题报告(Python)
[LeetCode]731. My Calendar II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...
- 【LeetCode】456. 132 Pattern 解题报告(Python)
[LeetCode]456. 132 Pattern 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...