你应该使用Python3里的这些新特性
概述
由于Python2的官方维护期即将结束,越来越多的Python项目从Python2切换到了Python3。可是,在实际的工作中,我发现好多人都是在用Python2的思维去写Python3的代码,Python3给我们提供了很多新的、很方便的特性,可以帮助我们快速的编写代码。
f-strings (3.6+)
在Python里面,我们经常使用format函数来格式化字符串,例如:
1 |
user = "Jane Doe" |
Python3里面提供了一个更加灵活方便的方法来格式化字符串,叫做f-strings。上面的代码可以这样实现:
1 |
user = "Jane Doe" |
Pathlib (3.4+)
f-strings这个功能太方便了,但是对于文件路劲这样的字符串,Python还提供了更加方便的处理方法。Pathlib是Python3提供的一个处理文件路劲的库。例如:
1 |
from pathlib import Path root = Path('post_sub_folder') |
Type hinting (3.5+)
静态与动态类型是软件工程中的一个热门话题,每个人都有不同的看法,Python作为一个动态类型语言,在Python3中也提供了Type hinting功能,例如:
1 |
def sentence_has_animal(sentence: str) -> bool: |
Enumerations (3.4+)
Python3提供的Enum类让你很容就能实现一个枚举类型:
1 |
from enum import Enum, auto class Monster(Enum): |
Python3的Enum还支持比较和迭代。
1 |
for monster in Monster: |
Built-in LRU cache (3.2+)
缓存是现在的软件领域经常使用的技术,Python3提供了一个lru_cache装饰器,来让你更好的使用缓存。下面有个实例:
1 |
import time def fib(number: int) -> int: |
现在我们可以使用lru_cache来优化我们上面的代码,降低代码执行时间。
1 |
from functools import lru_cache @lru_cache(maxsize=512) |
Extended iterable unpacking (3.0+)
废话不多说,直接上代码,文档在这
1 |
head, *body, tail = range(5) |
Data classes (3.7+)
Python3提供data class装饰器来让我们更好的处理数据对象,而不用去实现 init() 和 repr() 方法。假设如下的代码:
1 |
class Armor: def __init__(self, armor: float, description: str, level: int = 1): |
使用data class实现上面功能的代码,这么写:
1 |
from dataclasses import dataclass @dataclass |
Implicit namespace packages (3.3+)
通常情况下,Python通过把代码打成包(在目录中加入init.py实现)来复用,官方给的示例如下:
1 |
sound/ Top-level package |
在Python2里,如上的目录结构,每个目录都必须有init.py文件,一遍其他模块调用目录下的python代码,在Python3里,通过 Implicit Namespace Packages可是不使用__init__.py文件
1 |
sound/ Top-level package |
结语
这篇文章只列出了一下部分Python3的新功能,我希望这篇文章向您展示了部分您以前不知道的Python 3新功能,并且希望能帮助您编写更清晰,更直观的代码。
最新文章
- Android之mtk上传log
- [翻译]PYTHON中如何使用*ARGS和**KWARGS
- AngularJS---表达式
- 逆向分析AHpack
- (ios实战)ios调试总结(转载)
- 深入了解webservice_概念总结
- AJax学习一
- HDU 1280 前m大的数【哈希入门】
- Outlook将收到邮件的附件保存在磁盘
- 远程控制TOMCAT启动
- Java 中的 String 类常用方法
- java实现红包的分配算法
- SpringBoot返回date日期格式化,解决返回为TIMESTAMP时间戳格式或8小时时间差
- 初探React Hooks &; SSR改造
- day 7-20 视图,触发器,事务
- Spring Boot用Cxf的jax-ws开发WebService
- python3中的urllib.parse的常用方法
- 切勿用普通for循环遍历LinkedList
- Python-RabbitMQ(简单发送模型)
- 63. Unique Paths II (Graph; DP)