简单了解Python3里的一些新特性
作者:千锋Python唐唐君 发布时间:2022-09-22 21:32:23
概述
到2020年,Python2的官方维护期就要结束了,越来越多的Python项目从Python2切换到了Python3。其实在实际工作中,很多伙伴都还是在用Python2的思维写Python3的代码。给大家总结一下Python3一些新的更方便的特性!希望你们看完后也能高效率的编写代码
f-strings (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.
Python3里面提供了一个更加灵活方便的方法来格式化字符串,叫做f-strings。上面的代码可以这样实现:
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提供的一个处理文件路劲的库。例如:
from pathlib import Pathroot = 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功能,例如:
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类让你很容就能实现一个枚举类型:
from enum import Enum, autoclass Monster(Enum):
ZOMBIE = auto()
WARRIOR = auto()
BEAR = auto()print(Monster.ZOMBIE)输出: Monster.ZOMBIE
Python3的Enum还支持比较和迭代。
for monster in Monster:
print(monster)输出: Monster.ZOMBIE Monster.WARRIOR Monster.BEAR
Built-in LRU cache (3.2+)
缓存是现在的软件领域经常使用的技术,Python3提供了一个lru_cache装饰器,来让你更好的使用缓存。下面有个实例:
import timedef 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来优化我们上面的代码,降低代码执行时间。
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+)
代码如下:
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 classes (3.7+)
Python3提供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.4print(armor)# <__main__.Armor object at 0x7fc4800e2cf8>
使用data class实现上面功能的代码,这么写:
from dataclasses import dataclass@dataclassclass 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.4print(armor)# Armor(armor=5.2, description='Common armor.', level=2)
Implicit namespace packages (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
在Python2里,如上的目录结构,每个目录都必须有 init .py文件,一遍其他模块调用目录下的python代码,在Python3里,通过 Implicit Namespace Packages可是不使用__init__.py文件
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的新功能,希望你在看了这篇文章以后,学以致用,写出更清晰更直观的代码!
来源:https://www.cnblogs.com/cherry-tang/p/10917367.html


猜你喜欢
- 1.前言我在进行DEM数据的裁剪时,发现各个省的数据量非常大,比如说四川省的30m的DEM数据的大小为2G。考虑到有限的电脑磁盘空间,我对T
- 正则表达式是处理字符串的强大工具。作为一个概念而言,正则表达式对于Python来说并不是独有的。但是,Python中的正则表达式在实际使用过
- Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。要写出 Pythonic(优雅的、地道的、整洁的)代码
- python 实现自动远程登陆scp文件实例代码实现实例代码:#!/usr/bin/expectif {$argc!=3} {s
- 之前有聊过 golang 的协程,我发觉似乎还很理论,特别是在并发安全上,所以特结合网上的一些例子,来试验下go routine中 的 ch
- PyTorch创建自己的数据集图片文件在同一的文件夹下思路是继承 torch.utils.data.Dataset,并重点重写其 __get
- 本文研究的主要是Django1.10文档的深入学习,Applications基础部分的相关内容,具体介绍如下。Applications应用D
- 在上一篇文章中,我整理了pandas在数据合并和重塑中常用到的concat方法的使用说明。在这里,将接着介绍pandas中也常常用到的joi
- PHP 异常处理异常用于在指定的错误发生时改变脚本的正常流程。异常是什么异常处理用于在指定的错误(异常)情况发生时改变脚本的正常流程。这种情
- 经典字典使用函数dict:通过其他映射(比如其他字典)或者(键,值)这样的序列对建立字典。当然dict成为函数不是十分确切,它本质是一种类型
- 1.查询数据库当前进程的连接数: select count(*) from v$process; 2.查看数据库当前会话的连接数: elec
- 环境Python 3.7.4pymysql8.0.11 MySQL Community Server读取图片以二进制格式读取图片with o
- int connectDb() { EXEC SQL BEGIN DECLARE SECTION; char username[20]; c
- 本文实例讲述了php版本CKEditor 4和CKFinder安装及配置方法。分享给大家供大家参考,具体如下:下载并解压CKEditor 4
- 实际线上的场景比较复杂,当时涉及了truncate, delete 两个操作,经确认丢数据差不多7万多行,等停下来时,差不多又有共计1万多行
- 如何使用pytorch加载并读取COCO数据集 环境配置基础知识:元祖、字典、数组利用PyTorch读取COCO数据集利用PyTorch读取
- 根据 homebrew-brew 官方的解释得知,MongoDB 不再是开源的了,并且已经从 Homebrew中移除 #43770正是由于
- 本文实例分析了Python操作Access数据库基本步骤。分享给大家供大家参考,具体如下:Python编程语言的出现,带给开发人员非常大的好
- 这里就不给大家废话了,直接上代码,代码的解释都在注释里面,看不懂的也别来问我,好好学学基础知识去!# -*- coding: utf-8 -
- llama Index是什么《零开始带你入门人工智能系列》第一篇:还用什么chatpdf,让llama Index 帮你训练pdf。Llam