从 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新特性的更多相关文章

  1. 字符串格式的方法%s、format和python3.6新特性f-string和类型注解

    一.%s msg = '我叫%s,今年%s,性别%s' %('帅哥',18,'男') print(msg) # 我叫帅哥,今年18,性别男 二.format # 三种方式: # 第一种:按顺序接收参数 ...

  2. python3.8 新特性

    https://docs.python.org/3.8/whatsnew/3.8.html python 3.8的新功能本文解释了与3.7相比,python 3.8中的新特性. 有关完整的详细信息,请 ...

  3. Python3.8新特性--PositionalOnly参数

    “理论联系实惠,密切联系领导,表扬和自我表扬”——我就是老司机,曾经写文章教各位怎么打拼职场的老司机. 不记得没关系,只需要知道:有这么一位老司机, 穿上西装带大家打拼职场! 操起键盘带大家打磨技术! ...

  4. python3.6 新特性学习

    #支持类型提示 typing { def greeting(name: str) -> str: return 'Hello ' + name #在函数greeting中,参数名称的类型为str ...

  5. python3.8新特性

    海象运算符(赋值运算符) #原来 def choice(): s = ' jsadlk '.strip() res = isinstance(s, int) if res: return 'int' ...

  6. Python3.8新特性-- 海象操作符

    “理论联系实惠,密切联系领导,表扬和自我表扬”——我就是老司机,曾经写文章教各位怎么打拼职场的老司机. 不记得没关系,只需要知道:有这么一位老司机, 穿上西装带大家打拼职场! 操起键盘带大家打磨技术! ...

  7. Python3.X新特性之print和exec

    print print 现在是一个函数,不再是一个语句.<语法更为清晰> 实例1 打开文件 log.txt 以便进行写入并将对象指定给 fid.然后利用 print将一个字符串重定向给文件 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. pipeline配置前端项目

    vue pipeline { agent { label 'master'} options { timestamps() disableConcurrentBuilds() buildDiscard ...

  2. Log4j2再发新版本2.16.0,完全删除Message Lookups的支持,加固漏洞防御

    昨天,Apache Log4j 团队再次发布了新版本:2.16.0! 2.16.0 更新内容 默认禁用JNDI的访问,用户需要通过配置log4j2.enableJndi参数开启 默认允许协议限制为:j ...

  3. InnoDB学习(五)之MVCC多版本并发控制

    MVCC多版本并发控制,是一种数据库管理系统并发控制的方法.MVCC多版本并发控制下,数据库中的数据会有多个版本,分别对应不同的事务,从而达到事务之间并发数据的隔离.MVCC最大的优势是读不加锁,读写 ...

  4. LuoguP7714 「EZEC-10」排列排序 题解

    Content 给定一个 \(1\sim n\) 的一个排列 \(p\),你每次可以选择一个区间 \([l,r]\) 并花费 \(r-l+1\) 的代价将下标在这个区间内的所有数升序排序,求使得排列 ...

  5. Linux使用tar解压的时候去掉父级目录

    去除解压目录结构使用  --strip-components N 如: 压缩文件text.tar 中文件信息为 src/src1/src2/text.txt 运行 tar -zxvf text.tar ...

  6. 一种实用性较强的求IOU的算法(任意多边形之间的IOU)

    PS:要转载请注明出处,本人版权所有. PS: 这个只是基于<我自己>的理解, 如果和你的原则及想法相冲突,请谅解,勿喷. 前置说明   本文作为本人csdn blog的主站的备份.(Bl ...

  7. 【LeetCode】1151. Minimum Swaps to Group All 1's Together 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 滑动窗口 日期 题目地址:https://leetco ...

  8. 【九度OJ】题目1193:矩阵转置 解题报告

    [九度OJ]题目1193:矩阵转置 解题报告 标签(空格分隔): 九度OJ http://ac.jobdu.com/problem.php?pid=1193 题目描述: 输入一个N*N的矩阵,将其转置 ...

  9. poj 2566Bound Found(前缀和,尺取法)

    http://poj.org/problem?id=2566: Bound Found Time Limit: 5000MS   Memory Limit: 65536K Total Submissi ...

  10. idea使用教程-常用设置

    [1]进入设置: [2]设置主题: [3]编辑区的字体变大或者变小: [4]鼠标悬浮在代码上有提示: [5]自动导包和优化多余的包: 手动导包:快捷键:alt+enter 自动导包和优化多余的包: [ ...