概述

由于Python2的官方维护期即将结束,越来越多的Python项目从Python2切换到了Python3。可是,在实际的工作中,我发现好多人都是在用Python2的思维去写Python3的代码,Python3给我们提供了很多新的、很方便的特性,可以帮助我们快速的编写代码。

f-strings (3.6+)

在Python里面,我们经常使用format函数来格式化字符串,例如:

1
2
3
4
5
6
7
8
9
10
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.

Python3里面提供了一个更加灵活方便的方法来格式化字符串,叫做f-strings。上面的代码可以这样实现:

1
2
3
4
5
6
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.

Pathlib (3.4+)

f-strings这个功能太方便了,但是对于文件路劲这样的字符串,Python还提供了更加方便的处理方法。Pathlib是Python3提供的一个处理文件路劲的库。例如:

1
2
3
4
5
6
7
8
9
10
11
from pathlib import Path

root = Path('post_sub_folder')
print(root)
输出结果: post_sub_folder path = root / 'happy_user' # 输出绝对路劲
print(path.resolve())
输出结果:/root/post_sub_folder/happy_user

Type hinting (3.5+)

静态与动态类型是软件工程中的一个热门话题,每个人都有不同的看法,Python作为一个动态类型语言,在Python3中也提供了Type hinting功能,例如:

1
2
3
4
5
def sentence_has_animal(sentence: str) -> bool:
return "animal" in sentence sentence_has_animal("Donald had a farm without animals")
# True

Enumerations (3.4+)

Python3提供的Enum类让你很容就能实现一个枚举类型:

1
2
3
4
5
6
7
8
9
from enum import Enum, auto

class Monster(Enum):
ZOMBIE = auto()
WARRIOR = auto()
BEAR = auto() print(Monster.ZOMBIE)
输出: Monster.ZOMBIE

Python3的Enum还支持比较和迭代。

1
2
3
4
5
6
for monster in Monster:
print(monster) 输出: Monster.ZOMBIE
Monster.WARRIOR
Monster.BEAR

Built-in LRU cache (3.2+)

缓存是现在的软件领域经常使用的技术,Python3提供了一个lru_cache装饰器,来让你更好的使用缓存。下面有个实例:

1
2
3
4
5
6
7
8
9
10
11
12
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: 30.684099674224854s

现在我们可以使用lru_cache来优化我们上面的代码,降低代码执行时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
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: 6.866455078125e-05s

Extended iterable unpacking (3.0+)

废话不多说,直接上代码,文档在这

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 classes (3.7+)

Python3提供data class装饰器来让我们更好的处理数据对象,而不用去实现 init() 和 repr() 方法。假设如下的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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实现上面功能的代码,这么写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)
armor.power()
# 10.4 print(armor)
# Armor(armor=5.2, description='Common armor.', level=2)

Implicit namespace packages (3.3+)

通常情况下,Python通过把代码打成包(在目录中加入init.py实现)来复用,官方给的示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

在Python2里,如上的目录结构,每个目录都必须有init.py文件,一遍其他模块调用目录下的python代码,在Python3里,通过 Implicit Namespace Packages可是不使用__init__.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

结语

这篇文章只列出了一下部分Python3的新功能,我希望这篇文章向您展示了部分您以前不知道的Python 3新功能,并且希望能帮助您编写更清晰,更直观的代码。

[原文链接](http://www.bugcode.cn/2019/05/20/python3_new_func/)

你应该使用Python3里的这些新特性的更多相关文章

  1. Python3.x 常用的新特性

    Python3.x 常用的新特性 print() 是函数,不是一个语句 raw_input()输入函数,改为 input() Python 3 对文本和二进制数据做了更为清晰的区分. 文本由unico ...

  2. 关于python3.8的一些新特性的解析与代码演示

    python3.8测试版出来了,我们来介绍一些变动,代码演示一下,当然底层相关的细节变动就不介绍了 只允许传位置参数 还记得如果我们想让某些参数只能以关键字参数的方式传递该怎么做吗? def foo1 ...

  3. Python3中的新特性(3)——代码迁移与2to3

    1.将代码移植到Python2.6 建议任何要将代码移植到Python3的用户首先将代码移植到Python2.6.Python2.6不仅与Python2.5向后兼容,而且支持Python3中的部分新特 ...

  4. 初识 MySQL 5.6 新特性、功能

    背景: 之前介绍过 MySQL 5.5 新功能.参数,现在要用MySQL5.6,所以就学习和了解下MySQL5.6新的特性和功能,尽量避免踩坑.在后续的学习过程中文章也会不定时更新. 一:参数默认值的 ...

  5. SQL Server 2014 BI新特性(一)五个关键点带你了解Excel下的Data Explorer

    Data Explorer是即将发布的SQL Server 2014里的一个新特性,借助这个特性讲使企业中的自助式的商业智能变得更加的灵活,从而也降低了商业智能的门槛. 此文是在微软商业智能官方博客里 ...

  6. SQL Server 2014新特性:五个关键点带你了解Excel下的Data Explorer

    SQL Server 2014新特性:五个关键点带你了解Excel下的Data Explorer Data Explorer是即将发布的SQL Server 2014里的一个新特性,借助这个特性讲使企 ...

  7. Oracle 11gR2 RAC 新特性说明

    最近接触了一下Oracle 11g R2 的RAC,发现变化很大. 所以在自己动手做实验之前还是先研究下它的新特性比较好. 一.    官网介绍 先看一下Oracle 的官网文档里对RAC 新特性的一 ...

  8. 开源一周岁,MindSpore新特性巨量来袭

    摘要:MindSpore很多新特性与大家见面了,无论是在效率提升.易用性,还是创新方面,都是干货满满. 最近,AI计算框架是业界的热点,各大厂商纷纷投身AI框架的自研发,究其原因:AI框架在整个人工智 ...

  9. 相比于python2.6,python3.0的新特性。

    这篇文章主要介绍了相比于python2.6,python3.0的新特性.更详细的介绍请参见python3.0的文档. Common Stumbling Blocks 本段简单的列出容易使人出错的变动. ...

随机推荐

  1. 在Electron运行的页面使用CSS的calc导致应用卡死

    这几天发现运行在我们开发的Electron里面的网页有部分应用点击访问就会卡死,通过排除法定位到使用了CSS的calc方法,如下: <el-table height="calc(100 ...

  2. SMAP数据产品介绍与下载方法

    1 SMAP(Soil Moisture Active and Passive)数据介绍 SMAP baseline science data products在下面的表格中展示,这些数据产品可以从两 ...

  3. (一)MVC项目

    一.整体架构: 注:取自其他文章,最后的NewFile.html纯用于测试错误,完全不用. 二.具体代码: 1.User.java package common; public class User ...

  4. Linux 安装环境初始化检查 安装Nginx

    一 .阿里云 centos 6.8 32 位裸环境 实现:Linux Nginx mysql php redis 查看当前安装的服务 [root@iZgahlk1l73998Z etc]# servi ...

  5. mysql中mysql数据库丢失报错Can't open the mysql.plugin table

    180720 10:00:54 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it. 18 ...

  6. Python2 中字典实现的分析【翻译】

    在这片文章中会介绍 Python2 中字典的实现,Hash 冲突的解决方法以及在 C 语言中 Python 字典的具体结构,并分析了数据插入和删除的过程.翻译自python-dictionary-im ...

  7. elasticsearch7.1.1【win】下载安装

    下载:https://www.elastic.co/cn/downloads/elasticsearch 历史版本下载:https://www.elastic.co/cn/downloads/past ...

  8. Java的设计模式(2)--单例模式

    保证一个类仅有一个实例,并提供一个访问它的全局访问点. 好处:    (1)频繁使用的对象,可以省略new操作花费的时间,这对于那些重量级对象而言,是非常客观的一笔开销.    (2)由于new的次数 ...

  9. Laravel-admin图片本地上传配置问题

    先打开config/filesystems.php 修改添加其中的 'admin' => [ 'driver' => 'local', 'root' => public_path(' ...

  10. PHP切割整数工具,类似微信红包金额分配

    Composer地址:https://packagist.org/packages/werbenhu/php-number-slicing GitHub地址:https://github.com/we ...